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
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
You still need to provide the first parameter regardless of its 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.
Only one parameter of a function can be a default parameter.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With