Saturday, April 7, 2012

C# strings are reference types but behave in many ways like value types

They are just strange. If they were like other reference types then references to the heap could easily be bound between two strings making a test like this return true. (This test returns false because strings are freaky.)

[TestMethod]
public void TestMethod()
{
   string foo = "bar";
   string baz = foo;
   baz = "qux";
   Assert.AreEqual(foo,"qux");
}

 
 

This touches on the matter some and explains that a new reference is created for baz in the situation above so that foo and baz do not share a reference. In spite of the two seperate references on the heap, the test below will return true due to another exception in how strings work.

[TestMethod]
public void TestMethod()
{
   string foo = "bar";
   string baz = foo;
   Assert.AreEqual(foo,baz);
}

 
 

The weird ways of string make understanding the difference between value and reference types confusing. It is best to just remember that string is strange./p>

No comments:

Post a Comment