C# pass-by-value and reference type

If you are coming from C/C++ programming background. You would be accustomed with heavy use of pass by reference (or pass by pointer) as a way to improve the performance, update the variable passed in and reducing memory consumption. It is so common, that most C/C++ function written to be efficient would be passing by constant reference (if they do not wish to allow variable passed in get updated)

Like

void myFunction(const MyClass & param)


So, you are rest assured that variable pass in would not get updated.


For C#, there is no such thing as const reference. But, there is pass-by-ref, unsafe pointer and pass-by-value.
So, to ensure that your variable passed in to function not get updated. You would naturally think of using pass-by-value.

However, there is a catch for pass-by-value if your object is of reference type (class, interface, delegate, objet, string)

Value type variable store value but reference type variable store references to object. So, even the reference is passed by value in the function. The method can still use the reference it receive to
update the original object stored in the memory.

So,

MyClass o = new MyClass();
myFunction(o);
Debug.Assert(o.MyName != “123”) ; //assertion get thrown because object has been updated by function



Public void myFunction(MyClass o)
{
o.MyName = “123”
}

So, in short, do not update the variable pass in to the function if you do not intend to. Or simply, write a Clone function for your object and pass in clone object instead.

Comments

Popular posts from this blog

Clearcase check in/uncheck out all the checked out files script

MSSQL GROUP_CONCAT

Duplicating a local copy of project from TFS and making web software client factory to work