Thursday, May 10, 2018

Parameter by Value and reference


C# program that demonstrates parameter passing

using System;

class Program
{
    static void Main()
    {
        int val = 0;

        Example1(val);
        Console.WriteLine(val); // Still 0.

        Example2(ref val);
        Console.WriteLine(val); // Now 2.

        Example3(out val);
        Console.WriteLine(val); // Now 3.
    }

    static void Example1(int value)
    {
        value = 1;
    }

    static void Example2(ref int value)
    {
        value = 2;
    }

    static void Example3(out int value)
    {
        value = 3;
    }
}

Output

0
2
3

 
Notes, Example 1. Example1 uses value-passing semantics for its declaration. Therefore, when it changes the value of its parameter int, that only affects the local state of the method.
Notes, Example 2. Example2 uses the ref modifier for its int parameter. This informs the compiler that a reference to the actual variable (int val) is to be passed to Example2.
Note:
The ref keyword is used in the calling syntax in Main. When Example2 sets its parameter to 2, this is reflected in the Main method.

Notes, Example 3. Example3 uses out on its parameter. This has compile-time checking features. These involve definite assignment rules.
Finally:
Example3 sets its parameter to 3—this is reflected in the calling location.

Ref, out. What is the difference between ref and out? The difference is in the compiler's application of the definite assignment analysis step.
Important:
The compiler demands that an out parameter be "definitely assigned" before any exit. There is no such restriction with the ref.

No comments: