Niloofar Norouzi
Niloofar Norouzi

Reputation: 61

method with params

I wrote this method:

static long Sum(params int[] numbers)
{
    long result = default(int);

    for (int i = 0; i < numbers.Length; i++)
        result += numbers[i];

    return result;
}

I invoked method like this:

Console.WriteLine(Sum(5, 1, 4, 10));
Console.WriteLine(Sum());  // this should be an error
Console.WriteLine(Sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15));

I want the compiler to shows an error when I call the method without any parameters (like Sum()). How can I do this?

Upvotes: 6

Views: 1127

Answers (5)

Henk Holterman
Henk Holterman

Reputation: 273244

You could write

 static long Sum(int number1, params int[] numbers)
 {
     long result = number1;
     ....
 }

But then you would lose this option:

 int[] data = { 1, 2, 3 };
 long total = Sum(data);   // Error, but Sum(0, data) will work. 

Upvotes: 8

Jord&#227;o
Jord&#227;o

Reputation: 56467

Consider two overloads:

static long Sum(int head, params int[] tail) {
  if (tail == null) throw new ArgumentNullException("tail");
  return Sum(new int[] { head }.Concat(tail));
}

static long Sum(IEnumerable<int> numbers) {
  if (numbers == null) throw new ArgumentNullException("numbers");
  long result = 0;
  foreach (var number in numbers) {
    result += number;
  }
  return result;
}

Sample usage:

Console.WriteLine(Sum(5, 1, 4, 10));
//Console.WriteLine(Sum());  // Error: No overload for method 'Sum' takes 0 arguments
Console.WriteLine(Sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15));
int[] array = { 42, 43, 44 };
Console.WriteLine(Sum(array));

Upvotes: 2

ctorx
ctorx

Reputation: 6941

EDIT: Can't get compile time check using params...this will give you a runtime exception...

static long Sum(params int[] numbers)
{
    if(numbers == null || numbers.Length < 2)
    {
         throw new InvalidOperationException("You must provide at least two numbers to sum");
    }     

    long result = default(int);

    for (int i = 0; i < numbers.Length; i++)
         result += numbers[i];

    return result;
}

Upvotes: 2

InBetween
InBetween

Reputation: 32750

params requires at least one argument as its a syntactic sugar for array[] arguments. You need to:

Sum(null);

and handle the null case accordingly in your method.

Upvotes: -4

Snowbear
Snowbear

Reputation: 17274

Extract first parameter out of params to make it mandatory:

static long Sum(int firstSummand, params int[] numbers)

Upvotes: 13

Related Questions