Pages

Friday, 12 April 2013

Difference between OUT and REF Reference Types in C#

Difference between OUT and REF Reference Types in C#

Out is often preferred to ref. It ensures that you can avoid assigning the variable before passing it as an argument.

The out and the ref parameters are used to return values in the same variables that you pass as an argument of a method. These parameters are very useful when your method needs to return more than one value.

The C# language has strict rules regarding the passing of parameters by value and by reference. The default is to pass all parameters by value, even if those parameters are themselves references.

out and ref are pretty much the same - the only difference is that a variable you pass as an out parameter doesn't need to be initialised, and the method using the out parameter has to set it to something. out is often preferred to ref. It ensures that you can avoid assigning the variable before passing it as an argument.

int x;
Foo(out x); // OK

int y;
Foo(ref y); // Error


C# Example to show the usage of out and ref

using System;
class Program
{
    static void Main()
    {
      int val = 0;

      Example1(val);
      Console.WriteLine(val); // Still 0!

      Example2(ref val);
      Console.WriteLine(val); // Now 2!

      Example3(out val);
      Console.WriteLine(val); // Now 3!
    }

    static void Example1(int value)
    {
      value = 1;
    }

    static void Example2(ref int value)
    {
      value = 2;
    }

    static void Example3(out int value)
    {
      value = 3;
    }
}


Output
0
2
3

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.