C# pass by reference mechanism

In the previous C# tutorial, we discussed pass by value mechanism. In this C# tutorial, we are going to learn to pass by refresh mechanism in C# programming. In the pass by value, when a method is called, a new storage location is created for each value parameter but, In the pass by reference mechanism when a method is called, a new storage location is not created for each value parameter.

You can say opposite mechanism of C#.In the C# pass by value mechanism, It does not modify the original value but In the C# pass by reference, it modifies the original value.


If you are tried an example of pass by value it will be easy for you. A reference parameter is a reference to a memory location of a variable.


In C# programming, we declare the reference parameter using the ref keyword.


Let's create a swapping example of the variable parameter as reference.

using System.IO;
using System;

class PassByValue
    void swap(ref int x, ref int y) {
    int tmp = x;
    x = y;
    y = tmp;

    static void Main()
        int m = 8;
       int n = 17;
      PassByValue obj=new PassByValue();
   Console.WriteLine("Before swapping (m,n) evaluate to:"+m+" ,"+n);
    obj.swap(ref m,ref n);
    Console.WriteLine("After swapping (m,n) evaluate to::"+m+" ,"+n);

Execute the above C# program and you will get the result as output.


 Before swapping (m,n) evaluate to:8 ,17
After swapping (m,n) evaluate to::17 ,8

Support Us - Subscribe Now

free instagram followers free instagram likes