Ref And Out keyword In C#

Ref

Ref is used for returning a value from a method. It is used with method parameters and returns the same variable value that was passed in the method as a parameter. When you pass the 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 initialized 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 an unassigned local variable. That means you need to initialize the value of a variable.

Error

Example 2

public class Program  
{  
    public void GetNumber(ref int i)  
    {  
        i = i + 10;  
    }  

    public static void Main(string[] args)  
    {  
        int firstnumber; // must be initialized 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 the first number, then it will run without any error and the output should be like the following.

Cmd

Out

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

Note: If you made any changes at 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;  
        // 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 our parameter has been changed inside the method. So the output value will be 30.

Output

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


Similar Articles