C# pass by value mechanism

Pass by value is a default mechanism in C# programming. The value type parameters contain a copy of the actual value to the function. This is a default when passing the parameter to the function. In the previous tutorial, we discussed the C# function call. When the function call, the storage location is created for every parameter values.

The storage location stored the value of actual parameters. The seen looks the same as we pass parameter normally.

In the pass by value mechanism, the storage location is created definitely rather than in pass by reference value is not created whatever you give as an argument to a function, it will be copied into the scope of that function.

Example of C# pass by value -

using System.IO;
using System;

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

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


When the program executes, it gives the output.


Before swapping (m,n) evaluate to:6 ,10
After swapping (m,n) evaluate to::6 ,10 

In the above C# example the two arguments m,n are copied from the main “into” the scope of the function swap. This means that the swapping that occurs within that function “lives” until swap returns. In fact, m,n within the main still preserve their original values.


Please Share

Recommended Posts:-