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
Fiddle Demo
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
Fiddle Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With