Pass By Value and Pass By Reference

Now we are going to learn about what is the pass by value and pass by reference.
  • 2051

Introduction

A pass by value is the variables which is defined before the calling the function.

Example

class cbv
    {
        static void squarit(int x)
        {
            x *= x;
            System.Console.WriteLine("the value inside the method:{0}", x);
        }
        static void Main()
        {
            int n = 5;
            System.Console.WriteLine("the value before calling method:{0}",n);
            squarit(n);
            System.Console.WriteLine("the value after calling methoid:{0}:",n);
            System.Console.WriteLine("presss any key to exit:");
            System.Console.ReadKey();
        }
    }
}

Output:

Clipboard02.jpg

Pass by Reference

A pass by reference is the variables which is defined before the calling function.

Example:

  class cbv
    {
        static void squarit(ref  int x)
        {
            x *= x;
            System.Console.WriteLine("the value inside the method:{0}", x);
        }
        static void Main()
        {
            int n=5;
            System.Console.WriteLine("The value inside the method:{0}",n);
            squarit(ref n);

            System.Console.WriteLine("The value after calling the method:{0}",n);

            System.Console.WriteLine("presss any key to exit:");
            System.Console.ReadKey();
        }
    }
}

Output

Clipboard04.jpg

 

© 2020 DotNetHeaven. All rights reserved.