Importance of Ref and Out Keyword

Introduction

 
In this blog, we are discussing the importance of the Ref and Out keyword with the C# simple program. There are 3 important points to remember about the ref and out keywords. Let’s discuss them one by one
 
Out and Ref are C# keywords that help you to pass variable data to functions and methods by reference. Normally when we pass variable data to function it will be passed by value. Please check the below code snippet.
  1. public class Program {  
  2.     public static void incrementvalue(int value) {  
  3.         value++;  
  4.     }  
  5.     static void Main(string[] args) {  
  6.         int num = 10;  
  7.         incrementvalue(num);  
  8.         Console.WriteLine("After increment num vaiable value is " + num.ToString());  
  9.         Console.ReadLine();  
  10.     }  
  11. }  
 
After executing the above program, what is the value of num? Please check the below snapshot.
 
 
From the main method, we are calling incrementvalue method by passing an integer value. When I come out, my outside variable value is 10, which means whatever changes have happened to the inside variable it is not effected outside. 
 
Let’s try with the Ref keyword. Here I am passing variable data to method with help of ref keyword. Please check the below code snippet.
  1. public static void incrementvalue(ref int num) {  
  2.     num++;  
  3. }  
  4. static void Main(string[] args) {  
  5.     int num = 10;  
  6.     incrementvalue(ref num);  
  7.     Console.WriteLine("After increment num vaiable value is " + num.ToString());  
  8.     Console.ReadLine();  
  9. }  
 
Now we can see our outside variable also manipulated. Ref helps you to pass your variable with reference. Please check the below result. 
 
 
Let’s try with the Out Keyword.
 
Please check the below code snippet:
  1. public static void incrementvalue( out int  num)  
  2.  {  
  3.     num = 10;  
  4.     num++;  
  5.  }  
  6.   
  7.  static void Main(string[] args)  
  8.  {  
  9.  int num = 10;  
  10.  incrementvalue( out  num);  
  11.  Console.WriteLine("After increment num vaiable value is " + num.ToString ());  
  12.  Console.ReadLine();  
  13.  }  
When we use the out keyword, we need to initialize in called function, otherwise, the compiler will have an issue.Please check the below issue.
 
 
 
The major observation is that our keyword is bounded in a single way.
 
Please check the below snapshot for the result.
 
 
 

Summary

 
In this blog, we have discussed the ref and out keywords with a simple program. 
Next Recommended Reading C# - Ref Keyword