Difference between out and ref keyword in C#

CsharpServer Side ProgrammingProgramming

out keyword

out keyword is used to pass arguments to method as a reference type and is primary used when a method has to return multiple values. ref keyword is also used to pass arguments to method as reference type and is used when existing variable is to be modified in a method. Following is the valid usage of ref and out keywords in C#.

Example

 Live Demo

using System.IO;
using System;
public class Program {
   public static void update(out int a){
      a = 10;
   }
   public static void change(ref int d){
      d = 11;
   }
   public static void Main() {
      int b;
      int c = 9;
      Program p1 = new Program();
      update(out b);
      change(ref c);
      Console.WriteLine("Updated value is: {0}", b);
      Console.WriteLine("Changed value is: {0}", c);
   }
}

Output

Updated value is: 10
Changed value is: 11

Following are some of the important differences between ref and out keywords.

Sr. No.Keyref keywordout keyword
1Purposeref keyword is used when a called method has to update the passed parameter.out keyword is used when a called method has to update multiple parameter passed.
2Directionref keyword is used to pass data in bi-directional way.out keyword is used to get data in uni-directional way.
3InitializationBefore passing a variable as ref, it is required to be initialized otherwise compiler will throw error.No need to initialize variable if out keyword is used.
4InitializationIn called method, it is not required to initialize the parameter passed as ref.In called method, it is required to initialize the parameter passed as out.
raja
Published on 15-Apr-2020 06:48:45
Advertisements