public int Add2(int a, int b) => a + b;
public int Add3(int a, int b, int c) => a + b + c;
public int Add4 (int a,int b,int c,int d) => a + b + c + d;
How can we write these methods under a single method?
public int Add2(int a, int b) => a + b;
public int Add3(int a, int b, int c) => a + b + c;
public int Add4 (int a,int b,int c,int d) => a + b + c + d;
How can we write these methods under a single method?
Use params int[]
in your Add method and you can add as many numbers as you'd like.
Something like:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(Add(1, 2, 3, 4, 5));
}
public static int Add(params int[] numbers)
{
int sum = 0;
foreach (int n in numbers)
{
sum += n;
}
return sum;
}
}
Result:
15
With Linq
, the code get's shorter
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine(Add(1, 2, 3, 4, 5));
}
public static int Add(params int[] numbers)
{
return numbers.Sum();
}
}
Result:
15
Try optional arguments.
Write a method A with
Add (int a, int b, int c = 0, int d = 0) { }
Then based on value passed in c and d param do calculation.
The value a
and b
are always used in three functions. These values are mandatory in your function. The value c
and d
aren't always used. If you want to combine all of the functions, just make these values optional by giving them default value.
public int Add(int a, int b, int c = 0, int d = 0){
return a + b + c + d;
}
Yet-another-way..fun with Func
and (also) Linq
:)
static Func<int[], int> Add = ((i) => i.Sum());
public static void Main()
{
Console.WriteLine(Add.Invoke(new[] {1,2,3,4,5}));
Console.WriteLine(Add.Invoke(new[] {8}));
Console.WriteLine(Add.Invoke(new[] {-2, -4, 6}));
}
//15
//8
//0