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'};
}
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.
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;
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.
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.
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'});
}
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