Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

params Parameter with default parameter values [duplicate]

Tags:

c#

params

I've seen the params parameter more times than I can say and always removed it without thinking about it's meaning. Now I've learned its purpose. What I just learned is that the params parameter must be the last in the parameter list. But this is what I learned about the parameters that have a default value specified. Example:

MyMethod(string Name, int blah=0). 

So the question is if I need to specify a default value as above while needing to use params, can this be done? If so, which must be declared last? Example:

MyMethod(int blah=0, params string[] variableData). 

Thanks for your help again. James

like image 508
iDevJunkie Avatar asked Feb 28 '13 06:02

iDevJunkie


People also ask

Can parameters have default values?

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

Can we use default parameter to first parameter in JavaScript?

You still need to provide the first parameter regardless of its default value.

How do you set a parameter to default value?

The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.

How many parameters can be default parameters?

Only one parameter of a function can be a default parameter.


2 Answers

Your example is correct:

public void TestMethod(string name = "asdasd", params int[] items)
{
}

params has to be last, no matter what parameter are used before that.

like image 111
MarcinJuraszek Avatar answered Sep 20 '22 15:09

MarcinJuraszek


Yes, params are a special case here - they're the only situation in which a parameter without a default value can come after one with a default value.

However, you can't then call the method and take advantage of the params side of things (for a non-empty array) without also specifying the optional parameter:

MyMethod(5, "x", "y");                            // Fine, no defaulting
MyMethod(variableData: new string[] { "x", "y"}); // Default for blah
MyMethod();                                       // Default for blah, empty variableData
MyMethod(new string[] { "x, "y" });               // Invalid   
MyMethod("x", "y");                               // Invalid
like image 35
Jon Skeet Avatar answered Sep 21 '22 15:09

Jon Skeet