Tuesday 27 August 2013

What is “out” keyword in C#

What is “out” keyword in C#

“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. 
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 keyword
Console.WriteLine("The value of a is " + a); 
}

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

The program will result : The value of a is 12

No comments:

Post a Comment