Friday, December 21, 2012

ref and out parameters




 ref parameters

• The ref modifier causes arguments to be passed by reference
• The ref modifier has to be used in the method definition and the code that
   calls it
void RefFunction(ref int iP)
{
iP++;
}
Call statement:

int iNum = 10;
RefFunction(ref iNum);
// iNum is now 11

out parameters

• the out parameter is used in cases where you need to return a value from    a method, but not pass a value to the method.
• use out parameter to return more than one value from the method.
• out parameter will not have any initial values but must be assigned a value before the method terminates.
passing variable number of arguments
• Methods can have a variable number of arguments, called a parameter array
• params keyword declares parameter array
• This must be last argument of the method and there can be only one such
argument.
int Sum(params int[] aiArr) {
int iSum = 0;
foreach (int iNum in aiArr)
iSum += iNum;
return iSum;
}
int iTotal = Sum(13,87,34);

No comments:

Post a Comment