4
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?

Maxim Srour
  • 157
  • 1
  • 17
  • Please fix your formatting. https://stackoverflow.com/editing-help – 001 Jul 18 '18 at 03:37
  • 1
    Possible duplicate of [How can you use optional parameters in C#?](https://stackoverflow.com/questions/199761/how-can-you-use-optional-parameters-in-c) - `public int Add(int a, int b, int c=0, int d=0)`, I would guess. – Ken Y-N Jul 18 '18 at 03:39

4 Answers4

12

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

Shar1er80
  • 9,001
  • 2
  • 20
  • 29
3

Try optional arguments.

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments#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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user2667246
  • 31
  • 1
  • 2
1

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;
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
david
  • 3,225
  • 9
  • 30
  • 43
1

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
EdSF
  • 11,753
  • 6
  • 42
  • 83