Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method with params

Tags:

c#

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?

like image 968
Niloofar Norouzi Avatar asked May 27 '11 15:05

Niloofar Norouzi


People also ask

Can a method have parameters?

The parameters are used in the method body and at runtime will take on the values of the arguments that are passed in. Note: Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked.

How do you call a method using parameters?

There are two ways to call a method with parameters in java: Passing parameters of primtive data type and Passing parameters of reference data type. 4. in Java, Everything is passed by value whether it is reference data type or primitive data type.

What are params in Java?

Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma. The following example has a method that takes a String called fname as parameter.

What is params in C# with example?

In C#, params is a keyword which is used to specify a parameter that takes variable number of arguments. It is useful when we don't know the number of arguments prior. Only one params keyword is allowed and no additional parameter is permitted after params keyword in a function declaration.


2 Answers

Extract first parameter out of params to make it mandatory:

static long Sum(int firstSummand, params int[] numbers)
like image 195
Snowbear Avatar answered Oct 06 '22 16:10

Snowbear


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. 
like image 39
Henk Holterman Avatar answered Oct 06 '22 14:10

Henk Holterman