Object References in C#

I have been working with some code written by other developers and it appears that there is some confusion with using the ref prefix on object parameters passed to a function. The following example illustrates some of the code I came across:

using System;

 

namespace foo

{

      internal class MyClass

      {

            private int _x = 0;

           

            public int X

            {

                  get { return _x; }

                  set { _x = value; }

            }

      }

 

      class Class1

      {

            [STAThread]

            static void Main(string[] args)

            {

                  MyClass myObj = new MyClass();

                  Foo(ref myObj);

                  Console.WriteLine(myObj.X);

            }

 

            public static void Foo(ref MyClass instance)

            {

                  instance.X += 5;

            }

      }

}

 

Notice the use of the ref object parameter in the Foo method. Many developers make use of ref unnecessarily when they intend to change the content of an object instance passed to a method. 

 

By default, all parameters are passed by value in C#, which ensures that any changes to parameter values are lost upon leaving a method and the original values passed from the calling context are restored. This is achieved by making copies of values being passed on the stack before calling the method. Adding the ref prefix to a parameter instructs the compiler to write code to pass the address of the variable containing the value instead of the value itself. When in method scope, the compiled code can make changes to the value by implicitly dereferencing the address stored in the parameter.

 

Unlike C++, C# will not allow a developer to pass an object across the stack.

 

All object instances in C# are reference types. The following code produces two object references that points to the same object instance. Any changes made to the object using reference A are reflected also through B.

 

object A = new object();

object B = A;

Since all object instances are references then the myObj object instance, instantiated in the code at the beginning of this post, is a reference and can be passed to the Foo method without the need of the ref keyword. The method can still manipulate the contents of the object because it’s not changing the value of the parameter itself but what the object reference points to. If Foo was required to reassign the parameter to a new object instance then the ref keyword would be required because the object reference change would need to be preserved outside the Method scope.

 

The ref keyword should similarly be used when a method is to change the value of a primitive type being passed to a method.

 

The out keyword is similar to the ref keyword in that it allows a change to a passed parameter to be preserved after exiting a method, but out does not require a parameter to be assigned when entering a method. However, out does require a parameter to be assigned before exiting a method.

One thought on “Object References in C#

  1. Good example!!

    Really good example but try it with objects included into a generic list, it won’t work as you desire if you try to replace the whole object like this:

    objB = new Object { Property = 2 };
    objA = list.Find(fn => Property == 1);
    objA = ObjB;
    objC = list.Find(fn => Property == 2);

    Guess what is on objC?? A null reference, why??

Comments are closed.