Call by value and call by reference in C# full Explanation

 


Call by value and call by reference in C# full Explanation

In C#, parameters can be passed to methods either by value or by reference. Understanding the difference between call by value and call by reference is important when working with methods that modify the values of variables. Here's a full explanation of call by value and call by reference in C#:

 

1. Call by Value:

v  By default, C# uses call by value when passing parameters to methods.

v  When a parameter is passed by value, a copy of the parameter's value is made and passed to the method.

v  Any changes made to the parameter inside the method do not affect the original variable in the calling code.

v  Example:

    

     void Increment(int num)

     {

         num++;

     }

 

     int number = 5;

     Increment(number);  // Call by value

     Console.WriteLine(number);  // Output: 5 (original value unchanged)

    

 

v  In the example above, the `Increment` method takes an `int` parameter `num`. When the method is called with `number` as an argument, a copy of the value `5` is made and passed to the method. Inside the method, the value of `num` is incremented, but it does not affect the original `number` variable.

 

2. Call by Reference:

v  To pass parameters by reference, you can use the `ref` or `out` keywords in C#.

v  When a parameter is passed by reference, the memory address of the parameter is passed to the method, allowing the method to directly modify the value of the original variable.

v  Any changes made to the parameter inside the method affect the original variable in the calling code.

v  Example using `ref` keyword:

    

     void Increment(ref int num)

     {

         num++;

     }

 

     int number = 5;

     Increment(ref number);  // Call by reference using 'ref'

     Console.WriteLine(number);  // Output: 6 (original value modified)

    

 

v  In the example above, the `Increment` method takes an `int` parameter `num` with the `ref` keyword. When the method is called with `ref number`, the memory address of `number` is passed to the method. Inside the method, the value of `num` is incremented, directly modifying the original `number` variable.

 

v  The `out` keyword is similar to `ref`, but it is typically used when the method needs to assign a value to the parameter rather than reading its initial value.

 

It's important to note that when passing reference types (such as objects or arrays) by value, a copy of the reference is passed, not a copy of the actual object. Therefore, modifications to the object itself will be reflected outside the method. However, reassigning the reference will not affect the original reference in the calling code.

 

Understanding the distinction between call by value and call by reference is crucial for correctly manipulating variables and understanding how values are passed between methods in C#.

Post a Comment

0 Comments