Sunday, April 20, 2014

C# ref parameter

One of the most vague point in C.#NET is passing argument by reference, or shortly by ref.
Though it is very simple idea in passing arguments to function:


  • If argument is passed by reference then it represents link to the source data (Pointer in C).
    This is true for structures and classes.
  • Otherwise for a class copy of link is passed. And for a struct copy of whole struct is passed (except class property objects).

Take an example without ref:

 class Cat
 {
     public string Name {get;set;}
 }

 class Program
    {
        static void Main(string[] args)
        {
            var catOscar = new Cat { Name = "Oscar" };
            ChangeCatToSimba(catOscar);

            Console.WriteLine("Cat name: " + catOscar.Name);
            Console.ReadKey();
        }

        // By default copy of reference is passed (without ref keyword)
        // Same as copy of Pointer can be passed in C language
         private static void ChangeCatToSimba(Cat cat)
        {
            // reassign source will do nothing with Oscar
            cat = new Cat { Name = "Simba" };
        }
    }

And here is example with ref:
class Program
    {
        static void Main(string[] args)
        {
            var catOscar = new Cat { Name = "Oscar" };
            ChangeCatToSimba(ref catOscar);

            Console.WriteLine("Cat name: " + catOscar.Name);
            Console.ReadKey();
        }

        // Ref takes memory address reference to cat object
        private static void ChangeCatToSimba(ref Cat cat)
        {
            // reassign source
            cat = new Cat { Name = "Simba" };
        }
    }


In the first example (without ref) result is "Oscar". In the second example reassigning occurs and result is "Simba".

1 comment: