Method with parameters

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 called the method as follows:

 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 show an error when I call a method without any parameters (e.g. Sum() ). How can i do this?

+6
source share
5 answers

Extract the first parameter from params to make it mandatory:

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

You can write

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

But then you lose this option:

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

EDIT: Unable to run compile time check with parameters ... this will give you an exception at runtime ...

 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; } 
+2
source

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)); 
+2
source

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

 Sum(null); 

and handle the null case accordingly in your method.

-4
source

Source: https://habr.com/ru/post/889218/


All Articles