Introduction

Ref and Out are two keywords in C# which give us an opportunity to pass a variable in methods by reference.

Both are treated differently at run-time but they are treated the same at compile time.

Add a Class and implement the following code:

class Class3  
{  
   //Callee  
   static void Method1(int variable1)  
   {  
      variable1 = variable1 + 60;  
   }  
   //Caller  
   public static void Main()  
   {  
      int variable2 = 40;  
      Method1(variable2);  
      Console.WriteLine(variable2);  
      Console.ReadLine();  
   }  
}  

O/P - 40

Note

Whatever changes happened to variable1 in Method1() it is not going to reflect variable2. Hence, we could say that the data is passed by value.

Ref

Modify the class and use the ref keyword to pass by reference. In the below example, we can see that when we are working with variable1, we are actually working with variable2.

class Class3  
{  
   //Callee  
   static void Method1(ref int variable1)  
   {  
      variable1 = variable1 + 60;  
   }  
   //Caller  
    public static void Main()  
   {  
      int variable2 = 40;  
      Method1(ref variable2);  
      Console.WriteLine(variable2);  
      Console.ReadLine();  
   }  
}  

#c# #csharp #programming-c

Ref and Out are two keywords in C#
1.15 GEEK