What are Ref and Out Keyword in C#?


Ref Parameter

  • Ref keyword is used to a pass a variable as reference.
  • It must be initialized before passing it to method/function.
  • Original value changes when ref parameter is modified in method/function.

Example :

 int i = 1;
 Addition(ref i);
 Console.WriteLine(i);
 
 private static void Addition(ref int a)
  {
     a = a + 5;
  }


Output: 6
Out Parameter

    • Variable which is passing as Out param is optional to initialize.
    • The Out parameter ‘value’ must be assigned to before control leaves the current method.

      private static void Addition(out int value)
      {            
      }
      


      it will throw an exception.

private static void Addition(out int value)
{            
   value = 4;
}


it will run successfully.
Example :

 int i = 1; //initialization is optional
 Addition(out i);
 Console.WriteLine(i);
 
 private static void Addition(out int a)
  {
     a = 5;
  }


Output: 5