Possible Duplicate:
passing an empty array as default value of optional parameter in c#
I have a method that looks like below. Currently, the parameter tags
is NOT optional
void MyMethod(string[] tags=null) { tags= tags ?? new string[0]; /*More codes*/ }
I want to make parameter tags
optional, as per c#
, to make a parameter optional you can set a default value in method signature. I tried the following hacks but none worked.
Code that didn't work - 1
void MyMethod(string[] tags=new string[0]){}
Code that didn't work - 2
void MyMethod(string[] tags={}){}
Please suggest what I am missing.
I have already seen this question:
Passing an empty array as default value of an optional parameter
C does not support optional parameters.
Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list aren't supported.
By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.
Optional Parameters are parameters that can be specified, but are not required. This allows for functions that are more customizable, without requiring parameters that many users will not need.
The documentation for optional arguments says:
A default value must be one of the following types of expressions:
a constant expression;
an expression of the form
new ValType()
, whereValType
is a value type, such as anenum
or astruct
;an expression of the form
default(ValType)
, whereValType
is a value type.
Since new string[0]
is neither a constant expression nor a new
statement followed by a value type, it cannot be used as a default argument value.
The first code excerpt in your question is indeed a good workaround:
void MyMethod(string[] tags = null) { tags = tags ?? new string[0]; // Now do something with 'tags'... }
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