1.

Ref vs Out Keyword in C#

Answer»

Before passing a ref parameter, you must assign it to a value. However, before passing an out parameter, you don't need to assign it to a value.

  • Ref Parameter

A reference to a memory location of a variable. DECLARE the reference parameters using the ref keyword. A ref parameter is passed as a reference, not a value.

  • Out Parameter

With the out parameter, you can return two values from a function.

The following is an example of ref parameter:

using System; class Example {    static void Main()    {        string str1 = "one";        string str2 = "two";        string str3 = "three";        DISPLAY(ref str1);        Display(ref str2);        Display(ref str3);        Console.WriteLine(str1);        Console.WriteLine(str2);        Console.WriteLine(str3);    }    static void Display(ref string a)    {        if (a == "two")        {            a = null;        }        if (a == "three")        {            a = null;        }    } }

The output:

one

The following is an example of out parameter:

using System; class Example {    static bool DEMO(out int a)    {        a = 5;        return a >= 5;    }    static void Main()    {        if (Demo(out int a))        {            Console.WriteLine(a);        }    } }

The output WOULD be visible correctly on .NET 4.7 and above:

5


Discussion

No Comment Found