This article will demonstrate about differences between Ref and Out keywords in CSharp.

REF

Ref is used for returning value from method. It is used with method parameters and returns the same variable value that was passed in the method as parameter. When you pass ref parameter in the method, it must initialize the value of a variable.

Example 1

public class Program  
{  
  
    public void GetNumber(ref int i)  
    {  
        i = i + 10;  
    }  
    public static void Main(string[] args)  
    {  
        int firstnumber;  //must be initialize first before use           
  
        Program objProgram = new Program();  
        objProgram.GetNumber(ref firstnumber);  
        Console.WriteLine("The value is " + firstnumber);  
  
  
        Console.ReadLine();  
  
    }  
}  

 

See the above example, when you run the project, you will get an error, which clearly says that you are using unassigned local variable. That means you need to initialize the value of variable.

Unassigned Local Variable

Example 2

public class Program  
{  
    public void GetNumber(ref int i)  
    {  
        i = i + 10;  
    }  
    public static void Main(string[] args)  
    {  
        int firstnumber; // must be initialize first before  
        firstnumber = 10;  
  
        Program objProgram = new Program();  
        objProgram.GetNumber(ref firstnumber);  
  
        Console.WriteLine("The value is " + firstnumber);  
        Console.ReadLine();  
  
    }  
}  

 

When you run the above program after initializing the value of first number, then it will run without any error and output should be like the following:

Ref-Keyword-Output

OUT

Out is only something different from Ref. It is necessary to be initialized before the use of out parameter in the method. It is used with method parameters and returns the same variable value that was passed in the method as parameter. You can pass multiple out parameter inside the method.

Note: If you made any changes on the time of calling the function in arguments then it will reflect on the variables.

Example 3

public class Program  
{  
    public void GetNumber(out int i)  
    {  
        i = 20;  
        i = i + 10;  
    }  
    public static void Main(string[] args)  
    {  
        int firstnumber;  
        firstnumber = 10; //there is no need to initialize, you can initialize inside the method also.   
  
  
        Program objProgram = new Program();  
        objProgram.GetNumber(out firstnumber);  
  
        Console.WriteLine("The value is " + firstnumber);  
  
  
        Console.ReadLine();  
  
    }  
}  

 

See the above example you will find that the value of out parameter has been changed inside the method. So the output value will be 30.


Out Keyword
Thanks for reading this article, I hope you enjoyed it.