Different types of arguments in C# - val, ref, out

By Santhosh N

This explains about different type of arguments that can be passed to C# .Net methods.

We have three types of arguments that can be passed to C# methods:


1) Passing by val – this is the default and any change to the variable inside the function is limited to the method and not available outside the method.


2) Passing by ref – This is used to pass the variables to the method and any changes made within the method are persisted outside.


Ex:
class eggSample
{
    static void Incr(ref int i)
    {
        i += 10;
    }
    static void Main()
    {
         int n = 20;
        Incr(ref n);
        // value will be 30
    }
}

3) Passing by out – This is exactly same as Passing by ref except that passing by out does not require the variable to be initialized before passing where as passing by ref requires variable needs to be initialized before passing to the method.


Ex:
class eggSample
{
    static void Incr(out int i)
    {
        i = 10;
    }
    static void Main()
    {
         int n;
        Incr(out n);
        // value will be 10
    }
}

Different types of arguments in C# - val, ref, out  (1688 Views)