I'd like to make a small clarification because the following is an usual source of confusion among beginners to the language:
All reference types in C# (all types not derived from System.ValueType) are passed by reference, just as nvoigt points out. However they still can be passed by reference or by value with different results.
Code:
class foo {
public int value;
public foo(int val) { value = val; }
}
foo is a class type. As such it is a reference-type (not derived from System.ValueType, but from System.Object) and will always be passed by reference between caller and callee. So if I'm to write the following code, bar will indeed change:
Code:
void Main() {
foo bar = new foo(13);
Console.WriteLine(bar.value); // will print 13
ChangeBarByVal(bar);
Console.WriteLine(bar.value); // will print 31
}
static void ChangeBarByVal(foo f) { // foo being passed by-value
f.value = 31;
}
If I change my code to pass by reference, the same thing will happen.
Code:
void Main() {
foo bar = new foo(13);
Console.WriteLine(bar.value); // will print 13
ChangeBarByRef(ref bar);
Console.WriteLine(bar.value); // will print 31
}
static void ChangeBarByRef(ref foo f) { // foo being passed by-ref
f.value = 31;
}
The question thus is, why would I want to pass by ref, something that is always passed by ref? The real distinction between passing by val and by ref, when it comes to ref types is not in the ability to change the object state. This will always be guaranteed. But in the ability to reassign the object.
Code:
void Main() {
foo bar = new foo(13);
Console.WriteLine(bar.value); // will print 13
ChangeBarByValue(bar);
Console.WriteLine(bar.value); // will still print 13, not 31
ChangeBarByRef(ref bar);
Console.WriteLine(bar.value); // will print 65
}
static void ChangeBarByValue(foo f) { // foo being passed by-value
f = new foo(31);
}
static void ChangeBarByRef(ref foo f) { // foo being passed by-ref
f = new foo(65);
}
As you can see, passing by value won't allow you to reassign the object (change the instance to where your reference is pointing). But passing by ref will.