November 15th, 2008
Passing by Reference and Value in C# - 2

C# might look a lot like C++ but that doesn’t mean that everything is as it appears to be. There are some gotcha’s that can trip you up.
Passing values to a function or variable is as common as breathing air. In general there are two ways of passing a value:
- By value – the function or variable receives a copy of the value, and cannot modify the original.
- By reference – the function receives a reference to the original and is able to modify the original. In C++ this is done usually done through pointers (&value).
Although pointers still exist in C# you need to tag your code explicitly as “unsafe” and that opens many other cans of worms. So at first glance it looks like C# is passing everything by value. There isn’t a * or & in sight. But this is deceiving.
Only the build in types (int, float, double,string, structs) are passed by value. All classes are passed by reference.
int a;
int b;
a = 42;
b = a;
a = 30;
Console.WriteLine("Passed by value: {0}", b);
As expected this prints “42″.
As said, classes are passed by reference. If you are used to C++ forcing your to use a * to reference a pointer the following code might surprise you somewhat:
class Demo
{
int myValue = 0;
public int Value
{
set { myValue = value; }
get { return myValue; }
}
}
class MainClass
{
public static void Main(string[] args)
{
Demo one = new Demo();
Demo two = new Demo();
one.Value = 20;
two = one;
one.Value = 30;
Console.WriteLine("The value is {0}" , two.Value );
}
}
This will actually output “30″. Two is a reference to one so its contents are equivalent to one. The memory allocated for “two” is released as soon as we refer it to one in line 20.
If you are used to C++, it helps to think of this in C++ concepts:
Demo *one = new Demo();
Demo *two = new Demo();
one->Value = 20;
two = one;
one->Value = 30;
Image by Barbera L Slavin
Tags: Learn C#, refernence, value









Except where otherwise noted, content on this site is
February 11th, 2009 at 4:25 am
Are you sure a string is a basic type?
February 11th, 2009 at 8:18 am
Hi Frederik,
You got me. String is a build-in type, but not a basic type.
http://msdn.microsoft.com/en-us/library/ya5y69ds.aspx