Thursday, August 25, 2011

The difference between out and ref in C#

Posted by Rahul Kharde at 2:26 AM

Both the parameters passed by reference,
A ref parameter must first be initialized before being passed from the calling function to the called function.
But a out parameter need not be initialized, we can pass it directly
Normally while we are passing values to other methods it will pass copy of the values.

But we use ref or out Parameter it passes reference of values.
ref and out both allow the called method to modify a parameter. The difference between them is what happens before you make the call.
  • ref means that the parameter has a value on it before going into the function. The called function can read and or change the value any time. The parameter goes in, then comes out
  •  out means that the parameter has no official value before going into the function. The called function must initialize it. The parameter only goes out
Here's a more detailed list of the effects of each alternative:

Before calling the method:

ref: The called must set the value of the parameter before passing it to the called method.
out: The caller method is not required to set the value of the argument before calling the method. Most likely, you shouldn't. In fact, any current value is discarded.

During the call:

ref: The called method can read the argument at any time.
out: The called method must initialize the parameter before reading it.

Remoted calls:

ref: The current value is marshalled to the remote call. Extra performance cost.
out: Nothing is passed to the remote call. Faster.
Technically speaking, you could use always ref in place of out, but out allows you to be more precise about the meaning of the argument, and sometimes it can be a lot more efficient.

Example


public class Test
{
    public void TestRef(ref int value)
    {
        value = 20;
    }
    public void TestOut(out int value)
    {
        value = 30;
    }
}
//--ref
Test ObjTest = new Test();
int value1=10;
Response.Write("Before ref:"+value1);
ObjTest.TestRef(ref value1);
Response.Write("After ref:"+value1);

//--Out
int value2;
ObjTest.TestOut(out value2);
Response.Write("After Out :" + value2);

OUTPUT
Before ref : 10
After ref : 20
After Out : 30



If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!


Kindly Bookmark and Share it:

YOUR ADSENSE CODE GOES HERE

0 comments:

Have any question? Feel Free To Post Below:

 

Popular Posts

Recent Comments

© 2011. All Rights Reserved | Help to understand .Net | Template by Blogger Widgets

Home | About | Top