41
loading...
This website collects cookies to deliver better user experience
The article is suitable for anyone and everyone as long as you know what a method and an array is in C# !
params
keyword for a method parameter, and possibly by the end of this it should have skyrocketed into your top 3 favorite method parameter types.params
keyword is , simply put, a method parameter that can take a variable number of arguments - you can pass in anything from one to infinity or even none at all !! It doesn't matter !!params
keyword we can pass in multiple or none depending on our needs at the time. With this we can avoid having to write multiple overloads for our methods like the below example.// Multiple Overloads
static int AddAll(int a, int b)
{
return a + b;
}
static int AddAll(int a, int b, int c)
{
return a + b + c;
}
static int AddAll(int a, int b, int c, int d)
{
return a + b + c + d;
}
params
keyword you can just write// Method
static int AddAll(params int[] list)
{
int total = 0;
for (int i = 0; i < list.Length; i++)
{
total += list[i];
}
return total;
}
// Method Call
int sum0 = AddAll();
int sum2 = AddAll(2,5);
int sum3 = AddAll(2,5,7);
// Or Declare the array and pass it in
int[] nums = { 1,3,4,8 };
int sum4 = AddAll(nums);
static int AddAll(params int[] list){....}
int sum3 = AddAll(2,5,7);
int[] nums = { 1,3,4,8 };
int sum4 = AddAll(nums);
param
type per method.param
type must be the last parameter.
e.g.
static int AddAll(string name, params int[] list)
params
is the last argument. static int AddAll(params int[] list, string name)
params
type will not work together. params
must take single-dimensional array - a multi-dimensional one will throw an error. params
keyword.