
Hi Anu_dgr8,
Thanks for asking this nice question.
OUT parameter is the output value you expect from a function in which you pass the variable. In order to pass OUT parameter to the function, the variable must be defined and that variable must be assigned a new value inside the function.
REF parameter is in a way similar as OUT parameter however its not necessary to assign a new value to the variable inside the function. Look at the below code snippet. Notice that I have assigned a new value in the OutParameter function but in RefParamter function I may have opted not to assign a new value and in both case I will get a updated value of the myCount variable.
Generally OUT parameter is used when you are expecting a single value from the function, however REF is used when you have an instance of the object and you want to pass that object into multiple functions where the properties of the object needs to be changed or its method needs to be called.
int myCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
OutParameter(out myCount);
Response.Write("Value after output parameter: " + myCount);
myCount = 0;
RefParameter(ref myCount);
Response.Write("<br />Value after Ref parameter: " + myCount);
myCount = 0;
SimpleParameter(myCount);
Response.Write("<br />Value after simple parameter: " + myCount);
}
void OutParameter(out int count)
{
count = 20;
}
void RefParameter(ref int count)
{
// optional, I may opt not to change this value
count = 60;
}
void SimpleParameter(int count)
{
// this will have not affect
count = 50;
}
==============
The output will be
Value after output parameter: 20
Value after Ref parameter: 60
Value after simple parameter: 0
You can also have a look at http://stackoverflow.com/questions/135234/difference-between-ref-and-out-parameters-in-net where it is explained little differently in more details.
Thanks
Regards,
Sheo Narayan
http://www.dotnetfunda.com
Anu_dgr8, if this helps please login to Mark As Answer. | Alert Moderator