According to msdn definition
"The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the method is reflected in the underlying argument variable in the calling method. The value of a reference parameter is always the same as the value of the underlying argument variable."
It will be easy to understand by using a example.
protected void Page_Load(object sender, EventArgs e)
{
CallMethod();
}
private void Method1(ref string par)
{
// The value of parameter will be changed in the calling method
par = "Value Changed";
}
private void Method2(string para)
{
// The value of parameter will be unchanged in the calling method
// "Value not Changed" will only be assigned to the parameter inside the Method2 scope
para = "Value not Changed";
}
private void CallMethod()
{
string value = "Passing value";
Method1(ref value); // argument passed as ref
Response.Write(value+"<br/>");
Method2(value);
Response.Write(value);
}
OutPut:
Value Changed
Value Changed
We have two methods where one method uses a ref parameter and other one is not. In the CallMethod() we call both of these methods by passing the same parameter value "Value Changed" but the out put is "Value Changed" from both of the methods. So what happens is, the changes made within the method using the ref parameter are reflected in the underlying argument variable in the calling method and if you do not use ref then the value of passed parameter will be unchanged in the calling method.
Monday, December 3, 2012
ref Parameter in C#.NET
Subscribe to:
Post Comments (Atom)
No comments:
Write comments