The String is both a reference type and a value type in .NET
type and a reference type.
A typical reference type is stored on the heap, and a typical value type is
stored on the stack.
Classes are reference types, for example, Windows.Forms.Textbox
Numbers are value types, for example, Integer and Double.
Value types are able to be stored on the stack because they have a finite
length. Reference types have variable length. So for reference types, .NET
keeps a memory reference on the stack to a location on the heap where the
actual value is stored. This allows the stack to be very fast and compact
while still being able to store large values like a string variable that
contains the preamble to the Constitution.
An analogy: A comparison to Sqlserver variables is the difference betwnee
the char and the varchar data types. The char always has a fixed length, the
varchar does not.
So the string is a special animal. You can use it without always having to
use a constructor. Good thing, it would be a real pain to have to write:
String myStringVar1 = new("hello ");
String myStringVar2 = new("world");
String myStringVar3 = myStringVar1 + myStringVar2;
Instead, because string is a special case in .NET we can just write:
String myStringVar3 = "hello " + "world";
Comments
Going with your examples:
int myIntVar1 = new int(5);
But as you stated, there is simpler syntax:
int myIntVar1 = 5;
The important thing to understand is the syntax applies to value types and reference types because they are Primitive Types.
I'm studying for a .NET exam and I'm confused. I'm hoping one of you can clarify for me.
If I understand reference types correctly one reference type variable to another and change one of them - the other changes as well - as each references the same pointer to the heap. Yes?
IE:
string sTemp1 = "test";
string sTemp2 = sTemp1;
sTemp2 = "xxx";
Does stemp1 now = "xxx"? This is not my experience.
Does immutability factor into this somehow? Does immutability somehow give it the flabor of a value type?
Thanks,
Adam