Facts of Ref And Out Type Parameters in C#


Introduction

Parameters are initialized with a copy of the arguments; when we pass an argument to a method, this is true regardless of whether the parameter is a value type like int, int? (nullable) or a reference type. Look at the example given below, it is impossible to change the parameter to affect the value of the argument passed.

        static void Main(string[] args)
       
{
           
int num = 33;
           
myfunction(num);
           
Console.WriteLine(num);
           
Console.ReadKey();
       
}

        private static void myfunction(int rcnum)
       
{
           
rcnum++;
       
}

In the above example, the value to the console is 33 not 34. The myfunction method increments a copy of the argument named rcnum and not the original argument. C# Language provides the ref and out keywords to allow modification.

Ref Type Parameters

When we pass a parameter as a ref type to a method, the method refers to the same variable and changes are made that will affect the actual variable. If we add the ref prefix then the parameter becomes an alias for the actual argument rather than a copy of the argument. When we use the ref parameter, anything we do to the parameter also affects the original argument because the parameter and the argument both reference the same object. Look at the example given below:

        static void Main(string[] args)
       
{
           
int num = 33;
           
myfunction(ref num);
           
Console.WriteLine(num);
           
Console.ReadKey();
       
}

        private static void myfunction(ref int rcnum)
       
{
           
rcnum++;
       
}

In the above example, we have passed to the myfunction method a reference to the original argument rather than a copy of the original argument and because of this any changes the method makes also changes the original argument and results in 34 being displayed on the screen.

Out Type Parameters

A variable passed as an out parameter is similar to ref, but there are a few implementation differences when you use it in C#. An argument passed as ref must be initialized before it is passed to the method, whereas in case of out it is not necessary, but after a call to the method as an out parameter the variable must be initialized. Look at the example below which will clarify all your doubts:

        static void Main(string[] args)
       
{
           
int num;
           
myfunction(out num);
           
Console.WriteLine(num);
           
Console.ReadKey();
       
}

       
private static void myfunction(out int rcnum)
       
{
           
rcnum = 33;
       
}

In above example, we have not passed any value from the main method; this is the importance of the out type parameter.

Thanks for joining here.

HAVE A HAPPY CODING!!

Up Next
    Ebook Download
    View all
    Learn
    View all