Normally a method has a definite number of parameters and they are passed from the calling method. What if you are not sure of the number of parameters or want to be flexible in that. A Simple example can be a Adding machine - which adds any numbers sent .
It is possible to achieve that with params keyword -
private void AddAsManyNumbersAsUCan(params int[] numbers)
{
int iTotal = 0;
foreach (int i1 in numbers)
{
iTotal += i1;
}
Console.WriteLine("Sum of {0} numbers added to {1}",numbers.Length ,iTotal);
}
The above method accepts any number of arguments (provided they are of the same type). The method can be called like:
AddAsManyNumbersAsUCan();
AddAsManyNumbersAsUCan(1,2,3);
AddAsManyNumbersAsUCan(100,-1,23,2121,4562);
Will give the following output
You can change the type of the parameter to a generic one - List etc to have a broader use
hey man thanks,
ReplyDeleteyour blog is really useful.