Parameter passing in C#
Article to explain how parameter are passed in C#.
Parameters are means of passing values to a method.
There are four different ways of passing parameters to a method in C# which are as:
- Value
- Ref (reference)
- Out (reference)
- Params (parameter arrays)
Passing parameter by value
By default, parameters are passed by value. In this method a duplicate copy is made and sent to the called function. There are two copies of the variables. So if you change the value in the called method it won't be changed in the calling method.
We use this process when we want to use but don't want to change the values of the parameters passed.
Practical demonstration of passing parameter by value
using System;
namespace value_parameter
{
class Program
{
class XX
{
public int sum(int a, int b)
{
a = a + 10;
b = b + 20;
return (a + b);
}
}
static void Main(string[] args)
{
// local data members have to initialized as they are not initiated with class constructor
int a = 10, b = 20;
XX obj = new XX();
Console.WriteLine("sum of a and b is : " + obj.sum(a, b));
Console.WriteLine("Value of a is : " + a);
Console.WriteLine("Value of b is : " + b);
Console.ReadLine();
}
}
}
In the above code we changed the values of data member a and b but it is not reflected back in the calling method. As the parameters are default passed by value.
Passing parameter by ref
Passing parameters by ref uses the address of the actual parameters to the formal parameters. It requires ref keyword in front of variables to identify in both actual and formal parameters.
The process of ref is bidirectional i.e. we have to supply value to the formal parameters and we get back processed value.
We use this process when we want to use or change the values of the parameters passed.
Practical demonstration of passing parameter by ref
using System;
namespace ref_parameter
{
class Program
{
class XX
{
public int sum(ref int a, ref int b)
{
a = a + 10;
b = b + 20;
return (a + b);
}
}
static void Main(string[] args)
{
// local data members have to initialized as they are not initiated with class constructor
int a=10 , b=20 ;
XX obj = new XX();
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();
}
}
}
Passing parameter by out
Like reference parameters, output parameters don't create a new storage location and are passed by reference. It requires out keyword in front of variables to identify in both actual and formal parameters.
The process of out is unidirectional i.e. we don't have to supply value to the formal parameters but we get back processed value.

Comments
Join the conversation! Your thoughts help the community grow.