Yesterday I made a Blog about value and reference types and how they act. A string is also a reference type but does it act like an reference type?
some code:
Person p = new Person( "Jan" );
Persoon refP = p;
p.FirstName = "Kevin";
Console.WriteLine("My First person = " + p.FirstName);
Console.WriteLine("My reference= " + refP .FirstName);
Person is a class that is also an reference type. Now my code with a string:
string
test;test = "myFirstTest";
string test2 = test;
test2 = "mySecondTest";
MessageBox.Show("test = " + test + " en test2 = " + test2);
my output is not the output that a expect from a referencetype? How come, I don't know, could it be because I don't make a instance with the keyword new??
This is maybe a simple question but actually I don't know the answer. Can someone figure this out for me!
thanks K
AnttiPosted Dec 7, 2005, 2:08 AM
And second things second, of course you can. There are 8 public constructor overloads for String class.
Tricky one, Mr. Andersson. Hmm, question would be easy, if there was something like an assign operator overloading in C#. But there aren't.
I think that this value-type-like behaviour is because of the immutableness (what ever that means:)), when ever you "make modifications" to string, you get whole new string object, and of course those two strings are different in your example. But how is this achieved, im not that sure... It must be magic;)
Now when i think, string class must have some kind of an internal object management system, if you can use string that aren't explicitically initialized with "new". Or something...? That would contain checks like: if strRef1 is equal to strRef2, create new strRef2. It can't be that hard, can it? Can't think, must go to work:)
kevin AnderssonPosted Dec 5, 2005, 4:46 AM
Rendy WendiPosted Dec 5, 2005, 2:52 AM