HomeCSharpDifference between the out and ref keyword in C#

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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...