C# ref & out Keywords

Updated on     Kisan Patel

The ref and our keyword can be used to change the behavior of the method parameters. When we pass a variable to the method, the runtime generated a copy and passes that copy to the method.

For Example,

using System;

namespace ConsoleApp
{
    class Tester
    {
        public static void Main(string[] args)
        {
            int a = 3;
            Square(a);
            Console.WriteLine("The value of a is " + a);
        }

        public static int Square(int i)
        {
            return i = i * i;
        }
    }
}

c-sharp-value-types

Here, you can see we have create one method named “Square”. When we call method Square() in Main() method and pass a variable a then a copy of the variable a is passed to the Square method and not the variable a. Also, note that i is the local variable in Square() and a is the local variable in Main(). Hence, variables can be accessed within their containing methods only.

C# ref Keyword

C# provides a keyword, ref, which means argument to be passed by reference, not by value. So the effect of passing by reference is that any change to the parameter in the method is reflected in the underlying argument variable in the calling method.

To use a ref parameter, Both the method signature and calling method should be declared as ref keyword.

C# ref Keyword Example

using System;

namespace ConsoleApp
{
    class Tester
    {
        public static void Main(string[] args)
        {
            int a = 9;
            Square( ref a );
            Console.WriteLine("The value of a is " + a);
        }

        public static int Square( ref int i )
        {
            return i = i * i;
        }
    }
}

Here is the output of the above C# program…

c-sharp-ref-example

Note : In the case of the ref keyword, the variable must be initialized before passing it to the method by reference.

C# out Keyword

C# out and ref, both keyword indicate that the parameter is being passed by reference. However, when using the out keyword, is not necessary to initialize the variable.

C# out Keyword Example

using System;

namespace ConsoleApp
{
    class Tester
    {
        public static void Main(string[] args)
        {
            int a;
            Square( out a );
            Console.WriteLine("The value of a is " + a);
        }

        public static int Square( out int i )
        {
            return i = 4 * 4;
        }
    }
}

The output of the above C# program…

c-sharp-out-example


C#

Leave a Reply