Parameter types in C# (Value,out,ref and params)


Value parameters:

Value parameter is also called In parameter. A parameter declared with no modifiers is a
value parameter. Methods are permitted to assign new values to a value parameter. Such assignments only affect the local storage location and it has no effect on the actual argument given in the method invocation.

static void ParamMethod(int Param1)
{
Param1 = 100;
}
static void Main()
{
int Paravalue = 10;
ParamMethod(Paravalue);
Console.WriteLine(Paravalue);
}

//Here the output is 10

Reference Parameter:

Reference parameter declared with a ref modifier. It does not make a new storage location. Instead, a reference parameter represents the same storage location as the variable given as the argument in the method invocation. It should assigned to some value before it go for the method invocation.

static void ParamMethod(ref int Param1)
{
Param1 = 100;
}
static void Main()
{
int Paravalue = 10; //Here Paravalue should assign
ParamMethod(ref Paravalue);
Console.WriteLine(Paravalue);
}

//Here the output is 100

Output parameters:

Output parameter declared with an out. Similar to a reference parameter, an output parameter does not create a new storage location. Instead, an output parameter represents the same storage location as the variable given as the argument in the method invocation.Every output parameter of a method must be definitely assigned before the method returns.

static void ParamMethod(out int Param1)
{
Param1 = 100; //Here Param1 should assign
}
static void Main()
{
int Paravalue ;
ParamMethod(out Paravalue);
Console.WriteLine(Paravalue);
}

//Here the output is 100

Params:

The value passed for a "params" parameter can be either comma separated value list or a single dimensional array. "params" parameters are input only.

static int Summation(params int[] Param1)
{
int Sum =0;
foreach(int P in Param1)
{
Sum = Sum +P;
}
return Sum ;
}

static void Main()
{
Console.WriteLine(Summation(1,2,3));
}

//Here the output is 6

No comments: