Lokesh Darapureddy: Understand difference between C# ref and out keywords            
       
                                                               

Thursday, 22 February 2024

                               
                                                                   

                            Understand difference between C# ref and out keywords                        

                                                               
                       
C# ref vs out Parameters

Understand difference between C# ref and out keywords


Aspect ref out
Initialization Required No, must be initialized before passed No, must be assigned inside the method
Value Before Passing Yes, variable must have a value before passing No, variable can be uninitialized
Usage Inside Method Can use the variable's initial value Must assign a value before returning
Return Value Can return any value including the initial value Must assign a value before returning
Use Case Used when you want to pass a variable by reference and also allow the method to read or modify the variable Used when you want the method to assign a value to the variable and return it

  • ref: initialization required, Bi-directional.
  • out: initialization not required, Unidirectional(from method to caller)
Pass by Value Addition



int a = 5;
int b = 10;

int sum = 0;
int product = 0;

static void Addition(int a, int b, int sum, int product)
{
    sum = a + b;
    product = a * b;
}

Addition(a, b, sum, product);

Console.WriteLine(sum + " " + product);

/**
 * Output: 0 0
 * 
 * It does not work because the value of sum and product are changed inside method only.
 The values of sum and product outside the addition does not change.
 */
Pass by Reference using 'ref' Keyword

int a = 5;
int b = 10;

int sum = 0;
int product = 0;

static void Addition(int a, int b, ref int sum, ref int product)
{
    sum = a + b;
    product = a * b;
}

Addition(a, b, ref sum, ref product);

Console.WriteLine(sum + " " + product);

/**
 * Outptut: 15 50
 */

Pass by Output using 'out' Keyword

int a = 5;
int b = 10;

int sum = 0;
int product = 0;

static void Addition(int a, int b, out int sum, out int product)
{
    sum = a + b;
    product = a * b;
}

Addition(a, b, out sum, out product);

Console.WriteLine(sum + " " + product);

/**
 * Output: 15 50
 */


                   
                                   
               
                                           

0 Comments:

                       
                                                                                                           
                       

                           

Post a Comment

                       

                       

Subscribe to Post Comments [Atom]

                                       

                        << Home