Learn about Out and Ref keyword.

vishalneeraj-24503
Posted by vishalneeraj-24503 under C# category on | Points: 40 | Views : 941
Hi all,

In dot net, we can pass parameters in a function or a method in 3 ways.
1). by value
2). by ref and,
3). by out

Ref and Out both keywords are the same for getting values and give the same output. These keyword we pass as a parameter in a function or a method.

Note:- One thing we have to know about both keyword is:-

In case of OUT keyword, variable which is referenced as out in parameter should be
intialized INSIDE of function but not necessary to initialize.

In case of REF keyword, variable which is referenced as ref in parameter MUST be
intialized OUTSIDE of function otherwise will give error.

To understand,let's take an example:-

private void sum_with_out(int a, out int b)
{
try
{
b = a+a;
messagebox.show(b.tostring());
}
catch(exception ex)
{
throw ex;
}
}

private void sum_with_ref(int a, ref int b)
{
try
{
b = a+a;
messagebox.show(b.tostring());
}
catch(exception ex)
{
throw ex;
}
}

protected void btn_sum_with_out(object sender, eventargs e)
{
try
{
int a;
int b;

a = 10;

sum_with_out(a,out b);
}
catch
{
throw ex;
}
}

protected void btn_sum_with_ref(object sender, eventargs e)
{
try
{
int a;
int b;

a = 10;
b = 0;

sum_with_ref(a,ref b);
}
catch
{
throw ex;
}
}

//Output for OUT will be 10 and REF will be also 10.

As you can see we have not intialized variable b in btn_sum_with_out event but in btn_sum_with_ref we have initialized b as 0;

Comments or Responses

Login to post response