Saturday, July 07, 2007

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
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

4 comments:

Anonymous said...

Nice and easy to understand but not comparative discussion with ref keyword.

Regards,
Anmol.Gupta

Shiva said...

thanks, this was useful.

-Shiva
www.shivagaadu.blogspot.com

Shiva said...

Nice, was useful. thanks.

Anonymous said...

so the alternative is

namespace ConsoleApplication1
{

class Test
{

public static void Main()
{
int a =0; // may be left un-initialized
DoWork(ref a); // note out
Console.WriteLine("The value of a is " + a);
Console.ReadLine();
}

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


}

I prefer to initialize variables all the time as I consider it as good practice.

Most Recent Post

Community Updates

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape