Out And Ref

In this article I have tried to show the basic difference between the out and ref keywords.
 
In C# there are basic two types of data, one is value types and the other one is reference types. When we pass this data to any method via parameters both act differently. By default value types are passed by value and reference types pass their references.
 
Pass by value means, if we make changes on data in the calling method, no changes will reflect in the caller method.
 
Example
  1. static void Main(string[] args)  
  2.         {  
  3.             int Counter = 10;  
  4.             //display value before parsing  
  5.             Console.WriteLine($"Original Value: {Counter}");  
  6.             doSomething(Counter);  
  7.             //display value after parsing  
  8.             Console.WriteLine($"Value After Changing: {Counter}");  
  9.             Console.ReadLine();  
  10.         }  
  11.         static void doSomething(int number)  
  12.         {  
  13.             number = 80;  
  14.         }  
OUTPUT
 
 
We can see here changes made in the ‘doSomething’ method are not reflected in the original data. That is because it is passed by value. But what if we want to pass this value type as reference?
 
Out and ref keywords are used to pass value types as reference. So if we make changes on data in the calling method, all changes will reflect in the caller method also (original data).
 
To pass value types as reference we simply put (ref/out) keyword before the parameter in the definition of method, and while calling we have to put (ref/out) keyword before the variable name accordingly.
 
Example 
  1. static void Main(string[] args)  
  2.         {  
  3.             int Counter = 10;  
  4.             //display value before parsing  
  5.             Console.WriteLine($"Original Value: {Counter}");  
  6.             doSomething(ref Counter);  
  7.             //display value after parsing  
  8.             Console.WriteLine($"Value After Changing: {Counter}");  
  9.             Console.ReadLine();  
  10.         }  
  11.         static void doSomething(ref int number)  
  12.         {  
  13.             number = 80;  
  14.         }  
OUTPUT
 
 
Here changes made in the calling method are reflected since reference of the variable is passed to the method. We can have similar output by using out keyword also. The only difference between these two is, when we use ref keyword the original value of the variable is also passed to calling method, whereas in case of out keyword we have to assign new value to the variable in the calling method.
 
Let's understand this with an example,
 
 
We can clearly see that we have to initialize the variable if we use out keyword. And it is ok with ref keyword.
 
In this article we have learned the difference between out and ref, if you have any doubts feel free to comment below.