ref/out Keyword in c#

ref Keyword in c#
*************

Passing variables by value is the default. However, we can force the value parameter to be passed by reference.

Point to be kept in mind while using ref keyword.
variable “must” be initialized before it is passed into a method.


Example,
Without Using ref keyword
class Test
{
public static void Main()
{
int a = 3;
DoWork(a);
Console.WriteLine("The value of a is " + a);
}

public static void DoWork(int i)
{
i++;
}
}
The program will result in : The value of a is 3


Example, With the Use of ref keyword
class Test
{
public static void Main()
{
int a = 3; // must be initialized
DoWork(ref a); // note ref
Console.WriteLine("The value of a is " + a);
}

public static void DoWork(ref int i) // note ref
{
i++;
}
}
The program will result : The value of a is 4

out Keyword in c#
**************

out keyword is used for passing a variable for output purpose. It has same concept as ref keyword, but passing a ref parameter needs variable to be initialized while out parameter is passed without initialized. (Check diff)
It is useful when we want
to return more than one value from the method.

Point to be kept in mind while using out keyword.
You must assigned value to out parameter in method body, otherwise the method won’t compiled.

Example of “out keyword”:
class Test
{
public static void Main()
{
int a; // may be left un-initialized
DoWork(out a); // note out
Console.WriteLine("The value of a is " + a);
}

public static void DoWork(out int i) // note out
{
i=4; //must assigned value.
}
}

The program will result : The value of a is 4

Read Users' Comments (0)

0 Response to "ref/out Keyword in c#"

Post a Comment