Home » Difference between Ref and Out Keyword in C#

Difference between Ref and Out Keyword in C#

  • by

Ref and Out keywords are used to pass the argument to the function. These keywords can pass parameters by reference. Ref and Out keyword treated same at the compiled time but different at run time.

Ref Keyword

Ref keyword passes the argument by reference, It means when changes are made in the ref variable in the calling method, that time those changes are reflected in a variable.

Example:

namespace RefVsOut
{
    class Program
    {
        static void Main(string[] args)
        {
            string FName="Kavin";
            Console.WriteLine("Before Execution =" + FName);
            GetName(ref FName);
            Console.WriteLine("After Execution =" + FName);
            Console.ReadLine();
        }

        public static string GetName(ref string FName)
        {
            FName = "Sam M";
            return FName;
        }
    }
}

Output:

Out Keyword:

Out keyword is similar to the ref keyword. Out keyword passes the argument by reference.

Example

namespace RefVsOut
{
    class Program
    {
        static void Main(string[] args)
        {
            string FName="Kavin";
            Console.WriteLine("Before Execution =" + FName);
            GetName(out FName);
            Console.WriteLine("After Execution =" + FName);
            Console.ReadLine();
        }

        public static string GetName(out string FName)
        {
            FName = "Sam M";
            return FName;
        }
    }
}

Output:

Difference between Ref and Out keyword

RefOut
1. Argument must be initialized, before pass it to the method.1. It’s not mandatory to initialize the parameter before passing it to the method.
2. It is not mandatory to initialize the value of the parameter before returning from the calling method2. It is required to initialize the value of the parameter before returning from the calling function.
3. Use when passing method also needed to modify the data.3. Use when multiple values need to return from a function.
4. Ref keyword may pass the data is Bidirectional.4. Out keyword data pass is Unidirectional.

Need help?

Read this post again, if you have any confusion or else add your questions in Community

Tags: