Difference between the out and ref keyword in C#

To pass an argument by reference in C# , we use the keyword ref . There is also another keyword “out” which can also be used to pass an argument by reference .

Below is a sample code demonstrating the usage of the out and ref keyword.

class Employee
{
        /* usage of the pass by reference using the keyword out */
        public void SQRT1(out int i)
        {
            i = 10;
            i = i + i;
        }
        /* usage of the pass by reference using the keyword ref */
        public void SQRT2(ref int i)
        {
            i = 10;
            i = i + i;
        }
}
class Program
{
        public static void Main1()
        {
            Employee studentObj = new Employee();
            int i;
            studentObj.SQRT1(out i);
            int j=1;
            studentObj.SQRT2(ref j);
            Console.WriteLine("i: " + i);
        }
}

What is the difference between out and ref keyword in C# ?

The variable has to be initialized when it is passed by ref keyword . The variable need not be initialized when using the out keyword but the value should be assigned inside the calling function.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...