A Quick Answer About Reference Types

Reference types were created to make dealing with pointers a little bit easier. They hide away the details of the pointers, so that the programmer need not think about them. In many ways I think they’re awesome, because they really achieve that goal. The problem is that by abstracting away the details of the pointers they’re sometimes difficult to work with, because they can be a little bit confusing.

I received a comment about this topic on one of my ASP Alliance articles explaining value types and reference types in C#.

First of all the article is excellent.
But why the following program produces output as:: abc:xyz
it should produce xyz:xyz.
I am confused...Plz help
The Code:
string myName = "abc";
string authorName = null;
authorName = myName;
authorName = "xyz";
Console.WriteLine("{0}:{1}",myName,authorName);
Console.ReadLine();
The Actual Output:
abc:xyz
The Expected Output:
xyz:xyz
as it's areference type only one copy is shared between references.

How about if we take this step by step looking at the variables and their values, and I’ll be able to explain why the behavior is as you’ve found. First here is the code we’ll be looking at.

string myName = "Brendan";
string authorName = null;
authorName = myName;
authorName = "Enrick";
Console.WriteLine("{0}:{1}",myName,authorName);
Console.ReadLine();

We are expecting it to print out “Brendan:Enrick”.

Red is for the variables and orange is for referenced values for those variables.

ReferenceTypes1

Notice that when we set a variable equal to a literal string value we get a new location in memory, but when we set it equal to another variable all we are doing is copying the pointer to that memory location. However, when we then set that variable equal to a new literal value it doesn’t replace the old one for both since they each had a pointer. It just creates a new location in memory with that value and assigns a pointer to that variable.

The type of behavior that the writer of this code was trying to achieve could be handled by pointers very easily, but reference types take away control of pointers. Loss of freedom for the sake of safety one might say. Now that I’ve said that everyone will switch back to using c++ to get their pointers back.

Thank you for asking the questions saurabh. I hope this thoroughly answers your question. If you have any more, please feel free to ask them as well.

Comments