Sunday, October 3, 2010

Understanding the Reference Parameter in C #. How to passing reference parameter in console Application.

Reference parameter: -
A reference parameter is used for “by reference” parameter passing, in which the parameter act as an alias for a caller- provided argument. A reference parameter does not itself define a variable, but rather refers to the variable of the corresponding argument. Modifications of a reference impact the corresponding argument. A reference parameter is declared with a ref modifier.

The example:

using System;

namespace ref_parameter
{

class Test
{

class Test1
{

public int sum(ref int a, ref int b)
{

a = a + 30;

b = b + 40;

return (a + b);

}

}

static void Main(string[] args)
{

// local data members have to initialized as they are not initiated with class constructor

int a = 30, b = 40;

Test1 obj = new Test1();

Console.WriteLine("sum of a and b is : " + obj.sum(ref a, ref b));

Console.WriteLine("Value of a is : " + a);

Console.WriteLine("Value of b is : " + b);

Console.ReadLine();

}

}

}

The output of the program is:

sum of a and b is : 140
Value of a is : 60
Value of b is : 80


Note: -The ref keyword must be used in both the declaration of the formal parameter and in uses of it. The use of ref at the call site calls special attention to the parameter so that a developer reading the code will understand that the value of the argument could changes as result of the call.





What Other's are reading.
Understanding the passing value Parameter in C #.
Understanding the output Parameter in C #.
Understanding the Parameter array in C #.

No comments:

Recent Posts