.NET

Out Vs Ref

There are some basic differences in Out and Ref.

Out :  Passed by reference and it must be set by the called method, otherwise there will be compiler error.

e.g.

int x; // no need to assign any value as the method in which it will be passed as OUT , its method responsibility to set its value.

void OutEx(out int x)
{
//x should be set some value before exiting from this method other compiler error
}

Ref : Already assigned passed and no need to reset in the called method.

e.g.

int x = 0;//here x must be set before passing as ref, because its not guarantee that the method in which it is passed as Ref, will set.

void RefEx(ref int x)
{
// x is already set, so no need to set. but you change
}

Another benefit of out modifier :  It allows the caller to obtain multiple return values from a single method invocation.

Interviewer can ask in a different way like : If you have to return multiple values from a single method, what will you do. Simple answer is use Out modifier.

Categories: .NET, c#

Tagged as: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.