Advanced Advanced Options (C #)

The code below will be pretty cool if it works. However, I cannot compile it, so I assume that this will not work in any form?

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

The next best option is to simply do

 public void foo(char[] bar = null) { if (bar==null) bar = new {'a'}; } 
+7
source share
5 answers

No, It is Immpossible. The default value must be a compile time constant. The default value will be inserted into the caller, not the callee. Your code will be a problem if the caller does not have 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'}); } 
+5
source

No, because the optional default parameter values ​​must be constant.

Why are compilation time constants required for optional parameters in C # 4.0?

+1
source

This will never work, because char [] is not a value type, but rather a reference type. Only value types can have constants assigned to them in optional parameters. You cannot reference an object (e.g. an array) at compile time. (Null is the only valid value for an optional reference type.)

+1
source

only with type values ​​can you set a default value for a parameter for compile-time constants (which makes it optional). For reference types, only strings have this ability. Other types can only be set to null.

edit : thanks @Martinho Fernandes for pointing this out. For value types, only compile-time constants are allowed

+1
source

Other comments also apply, but also keep in mind that since the default value is inserted into the calling object at compile time, changing the default value at some later date will not change the value in the caller’s code (provided that it is called from another assembly.) Because of this, what you offer as a working or next best option is actually a better practice.

+1
source

All Articles