Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optional array Parameter in C# [duplicate]

Tags:

c#

c#-4.0

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

like image 701
Rusi Nova Avatar asked Nov 21 '11 14:11

Rusi Nova


People also ask

Can you have optional parameter in C?

C does not support optional parameters.

What is the optional parameter?

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.

Can you make a parameter optional?

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.

What are optional parameters are added?

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.


1 Answers

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(), where ValType is a value type, such as an enum or a struct;

  • an expression of the form default(ValType), where ValType 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'... } 
like image 156
Frédéric Hamidi Avatar answered Sep 23 '22 03:09

Frédéric Hamidi