ref and out keywords in C #

ref and out keywords in C #

Introduction

By default, a function or method accepts parameters passed by value. But with ref and out keywords, you can pass the parameters by reference. This means that any modification made to parameters passed is reflected in the calling method. This can be helpful in a situation where you want to return more than one value from a function.

ref keyword

The ref keyword is used to pass parameters to a function or method by reference.

class Program
{
    static void MyFun(ref int a)
    {
        a++;
    }
    static void Main(string[] args)
    {
        int a = 10;
        Console.WriteLine(a);
        MyFun(ref a);
        Console.WriteLine(a);
        Console.ReadKey();
    }
}

Output

10 11

out keyword

The out keyword is also used to pass parameters by reference. Now you might be thinking why we have two keywords for the same purpose? The answer is simple. Even though the two keywords are used to pass parameters by reference, out keyword can be used to pass parameters that are not initialized.

Here’s an example:

class Program
{
    static void MyFun(out int a)
    {
        a=10;
    }
    static void Main(string[] args)
    {
        int a;
        MyFun(out a);
        Console.WriteLine(a);
        Console.ReadKey();
    }
}

Output

10

If you enjoyed this post, let me know by leaving a comment below.

0 Comments
Loading...