Some times we may require a method which can accept variable number of arguments.
C# provides the params keyword for this purpose. The syntax for using params keyword is
params datatype[] argument name
For using the params keyword the argument must be declared as single dimensional array.Once an argument is prefixed with the params keyword, C# will accept any number of values (including none)for that argument.
Example
public class Test { public int Sum(params int[] num) { int totval = 0; foreach (int n in num) { totval += n; } return totval; }
public static int Main(string[] args) { Test T = new Test();
Console.WriteLine(T.Sum()); Console.WriteLine(T.Sum(3,2)); Console.WriteLine(T.Sum(50,60,100,150)); return 0; } }
The output of the above program will be 0 5 360
|
No responses found. Be the first to respond and make money from revenue sharing program.
|