By value, by reference: by analogy
Here’s my best attempt to explain C# value types and reference types, and “pass by value” and “pass by reference” to a newbie. (Not you, of course.)
Value types
A piece of paper, on which is written the number 5. You use this number to calculate something.
Reference types
A piece of paper, on which is written a memory location. You then go to the memory location in order to access an object.
(Aside: the “object reference not set to an instance of an object” exception means that the piece of paper has the special value of “unspecified”, and when you try to use this piece of paper to access an object, you aren’t able to.)
(Another aside: in C#, by default, you aren’t able to do anything with references except to use it to access an object. In C and C++, however, you could perform arithmetic on references – powerful and dangerous.)
Pass by value
I’m a function. You hand me a piece of paper. I take out my own piece of paper, copy down what’s written on your piece of paper, and give your piece of paper back to you. Whatever I scribble on my piece of paper doesn’t affect your piece of paper.
Pass by reference
I’m a function. You hand me a piece of paper. I write on your piece of paper and give it back to you. Your piece of paper is definitely affected.
Passing reference types by value
I’m a function. You hand me a piece of paper with a memory location written on it. I take out my own piece of paper, copy down the memory location, and give your piece of paper back to you. I can’t change what’s on your piece of paper, but I can affect your object.
Passing reference types by reference
I’m a function. You hand me a piece of paper with a memory location written on it. I rub out the memory location, write a new memory location, and give back the piece of paper to you. You are now referencing another object in the new memory location.
Strings
Strings are a special case. Technically they’re reference types, but for the sake of convenience, we’re able to treat strings as value types. Although we’re passing the memory locations of our strings to functions, we don’t have to worry about these functions modifying our strings. This is because strings are immutable, like so:
class ImmutableType
{
private int _value;
public ImmutableType(int value)
{
_value = value;
}
public int Value
{
get
{
return _value;
}
}
}
class Program
{
public static void Main()
{
ImmutableType x = new ImmutableType(5);
// will output 5
Console.WriteLine(x.Value);
// set y to refer to the same object as x
ImmutableType y = x;
// will output 5
Console.WriteLine(y.Value);
// illegal, no set accessor, so our object is safe
//y.Value = 6;
// no choice but to create a new object
y = new ImmutableType(6);
}
}
One Response to “By value, by reference: by analogy”
1 dirn 23 April 2010 @ 1:40 am
hahaha…nice analogy!!!
Comments: