Parameter passing in C#

What is parameter passing?

The parameter passing is nothing but passing a value or reference to method.
The parameter passing can be two types in c#. They are
  1. Value type parameter passing
  2. Reference type parameter passing

Value type parameter passing:

In value type parameter passing we passing the value to method like,

class Program

{

    static void Main(string[] args)

    {

        Program p = new Program();

        p.method(2, 3);//pass by value

    }

    void method(int i, int j)

    {

         Console.WriteLine("pass by value : "+(i + j).ToString());

    }

}
Reference type parameter passing:

In reference parameter passing passing the varible or object reference to method.

class Program

{

    static void Main(string[] args)

    {

        int i = 5, j = 5;

        method1(ref i, ref j); //pass by ref

    }

    static void method1(ref int i, ref int j)

    {

        Console.WriteLine("pass by reference : " + ((i+1) + (j+1)).ToString());

    }

}
When we passing reference we can change the value of that variable.(i.e) here we passing i and j value to method1.so there we can change the i and j value.by we can't do this in value passing.
Output parameter passing:

The output parameter passing is same like reference parameter . the simple difference is when you using output parameter no need to assign value to variable.

class Program

{

    static void Main(string[] args)

    {

        int i = 5, j = 5,i1,j1;

        method2(out i1,out j1);//output parameter

    }

    static void method2(out int i, out int j)

    {

        i=10;j=10;

        Console.WriteLine("output parameter : " + (i + j).ToString());

    }

}
Parameter array passing:

The parameter array can pass value and reference as array.

class Program

{

    static void Main(string[] args)

    {   

        int[] x = { 1, 2, 3 };

        method3(x);

        method3(4, 5);

    }

    foreach (int x in numbers)

    {

        Console.Write(x + " ");

    }      

    Console.ReadLine();

}

Ebook Download
View all
Learn
View all