Wednesday, July 20, 2011

Pass by Value and Pass by Reference in C#

This article is a quick explanation of C#'s handling of pass-by-val and pass-by-ref. If you haven't already done so, it's a worth getting to grips with the heap and the stack - that article will also explain the relationship between value types, reference types and pointers, which will be really useful.

Value-Types
By default, value types are 'passed-by-value' into C# methods. This means that inside the body of the called method, the value instance can be changed or re-assigned without affecting the instance of the value in the caller.

static void Main(string[] args)
{
    int i = 1;
    Console.WriteLine(i); // prints 1
    MyMethod(i);
    Console.WriteLine(i); // prints 1
}

static void MyMethod(int i)
{
    i = 2;
}

If you want to override this behaviour, you can use the ref keyword or out keyword:

static void Main(string[] args)
{
    int i = 1;
    Console.WriteLine(i); // prints 1
    MyMethod(ref i);
    Console.WriteLine(i); // prints 2
}

static void MyMethod(ref int i)
{
    i = 2;
}

You can use the ref or the out keyword, the only difference it makes is that ref needs the value to have been initialised before it is passed.

The compiler will issue an error if you try to send an unassigned variable with the ref keyword, but it will let you send happily using out. Ofcourse, if you don't have logic to handle the unassigned out variable in the target method you will get a runtime exception anyway.

Reference-Types
There really is no way to pass reference-types other than by reference. So although you can use the out and ref keywords with an object, there really isn't much point:

static void Main(string[] args)
{
    MyClass myObj = new MyClass();
    MyMethod(ref myObj);            //not much point
}

If you want to pass a reference-type variable by-value, you need to start thinking about cloning the object, which is a whole new subject matter in itself. If you simply want to prevent the passing object from being altered you might want to consider making the class immutable, but in any case that's outside the scope of this article.

More examples

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.