C# pass by value/ref?

As @rstevens answered, if it is a class, myCat is a reference. But if you pass myCat to a method call, then the reference itself is passed by value - i.e. the parameter itself will reference the same object, but it's a completely new reference, so if you assign it to null, or create a new object, the old myCat reference will still point to the original object.

SomeMethod(myCat);

void SomeMethod(Cat cat)
{
    cat.Miau(); //will make the original myCat object to miau
    cat = null; //only cat is set to null, myCat still points to the original object
}

Jon Skeet has a good article about it.


Remember that a pointer is not exactly the same as a reference, but you can just about think of it that way if you want.

I swear I saw another SO question on this not 10 minutes ago, but I can't find the link now. In the other question I saw, they were talking about passing arguments by ref vs by value, and it came down to this:

By default in .Net, you don't pass objects by reference. You pass references to objects by value.

The difference is subtle but important, especially if, for example, you want to assign to your passed object in the method.


If you delacred Cat as

class Cat {...}

then it is.

If you delcared Cat as

struct Cat {...}

then your variable "is" the structure itself.

This is the difference between reference types and value types in .Net.

Tags:

C#