Given these three similar methods, how we can condense them into a single method?

  • A+
Category:Languages
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

Enhancement

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: