Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advanced Optional Parameters (c#) [duplicate]

The below code would be quite cool if it worked. However, I can't get it to compile, so I'm assuming this isn't going to work in any form?

public void foo(char[] bar = new char[]{'a'})
{
}

The next-best option is to just do

public void foo(char[] bar = null)
{
   if (bar==null)
      bar = new {'a'};
}
like image 432
maxp Avatar asked Mar 22 '11 12:03

maxp


People also ask

What happens if we do not pass any parameter to optional arguments?

If we do not pass any parameter to the optional arguments, then it takes its default value. The default value of an optional parameter is a constant expression. The optional parameters are always defined at the end of the parameter list. Or in other words, the last parameter of the method, constructor, etc. is the optional parameter.

What is the default value of an optional parameter?

Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. 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;

How are optional parameters defined in Python?

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.

How do I declare optional parameters in a class?

You can also declare optional parameters by using the .NET OptionalAttribute class. OptionalAttribute parameters do not require a default value. In the following example, the constructor for ExampleClass has one parameter, which is optional.


1 Answers

No it's not possible. The default value needs to be a compile-time constant. The default value will be inserted into the caller, not the callee. Your code would be a problem if the caller has no access to the methods used to create your default value.

But you can use simple overloads:

public void foo(char[] bar)
{
}

public void foo()
{
  foo(new char[]{'a'});
}
like image 65
CodesInChaos Avatar answered Oct 13 '22 07:10

CodesInChaos