YouTip LogoYouTip

Csharp Param Arrays

# C# Parameter Arrays [![Image 3: C# Arrays](#) C# Arrays](#) Sometimes, when declaring a method, you cannot be certain of the number of arguments to pass to the function as parameters. C# parameter arrays solve this problem. Parameter arrays are typically used to pass an unknown number of arguments to a function. ## The params Keyword When using an array as a formal parameter, C# provides the `params` keyword. This allows a method with an array as a formal parameter to be called either by passing an array argument or by passing a list of array elements. The syntax for using `params` is: public ReturnType MethodName( params TypeName[] ArrayName ) ## Example The following example demonstrates how to use parameter arrays: ## Example using System; namespace ArrayApplication { class ParamArray { public int AddElements(params int[] arr) { int sum =0; foreach(int i in arr) { sum += i; } return sum; } } class TestClass { static void Main(string[] args) { ParamArray app =new ParamArray(); int sum = app.AddElements(512, 720, 250, 567, 889); Console.WriteLine("Sum is: {0}", sum); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result: Sum is: 2938 [![Image 4: C# Arrays](#) C# Arrays](#)
← Csharp Array ClassCsharp Passing Arrays To Funct β†’