Monday, May 21, 2007

Reference and Value Parameters

What is the Value Parameter? Explain with the example?
When used parameters that you have passed a value into a variable used by the function. Any changes made to this variable in the function have no effect on the parameter specified in the function call.
Example, consider a function that doubles and displays the value of a passed parameter:
Static void ShowDouble (int val)
{
val *= 2;
Console.WriteLine (“val doubled = {0}”, val);
}
Here the parameter, val, is doubled in this function. If you call it in the following way:
int myNumber = 5;
Console.WriteLine (“myNumber = {0}”, myNumber);
ShowDouble(myNumber);
Console.WriteLine (“myNumber = {0}”, myNumber);
Result is:
myNumber = 5
val Double = 10
myNumber = 5
So here calling the ShowDouble() with myNumber as a parameter doesn’t affect the value of myNumber in Main(), even though the parameter it is assigned to, val is doubled.

What is the Reference Parameter? Explain with the example?
Passing the parameter by reference will help you to change the values of multiple variables. Any changes made to this variable will, therefore, be reflected in the value of the variable used as a parameter. To do this, you simply have to use the ref keyword to specify the parameter.
Example:
Static void ShowDouble ( ref int val)
{
val *= 2;
Console.WriteLine (“val doubled = {0}”, val);
}
Here the parameter, val, is doubled in this function. If you call it in the following way:
int myNumber = 5;
Console.WriteLine (“myNumber = {0}”, myNumber);
ShowDouble(myNumber);
Console.WriteLine (“myNumber = {0}”, myNumber);
Result is:
myNumber = 5
val Double = 10
myNumber = 10
This time the myNumber has been modified by ShowDouble().

What are the limitations on the variable used as a ref parameter?
· Results in a change to the value of a reference parameter, so you must use a nonconstant variable in the function call. For example this is illegal:
Const int myNumber = 5;
Console.WriteLine (“myNumber = {0}”, myNumber);
ShowDouble(myNumber);
Console.WriteLine (“myNumber = {0}”, myNumber);

· You must use an initialized variable. C#$ doesn’t allow you to assume that a ref parameter will be initialized in the function that uses it. The following code is illegal:
int myNumber;
Console.WriteLine (“myNumber = {0}”, myNumber);
ShowDouble(myNumber);
Console.WriteLine (“myNumber = {0}”, myNumber);

No comments: