Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 268
Devaraneni Laxman Rao Avatar asked Dec 03 '22 11:12

Devaraneni Laxman Rao


1 Answers

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

like image 163
Shar1er80 Avatar answered Feb 02 '23 00:02

Shar1er80