Collection Literals – Possible to satisfy compile-time constant requirement? #7484
-
Would it be possible to allow collection literals to be passed, for example, as default parameters? Something like this: void M(int[] foo = [ ]) { } today throws the compiler error It would be fantastic to see this working one day. |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 5 replies
-
The limitation is from compiled assembly encoding, not the compile-time constant check. Currently, no collection type can be encoded in constants. However for attributes we can encode array. Collection expressions may be permitted there. |
Beta Was this translation helpful? Give feedback.
-
There is no way that that can be constant. Consider:
If this was constant, you'd now be mutating the constant value. |
Beta Was this translation helpful? Give feedback.
-
@just-ero - for situations like that, you might consider using a functor approach or an args object with defaults on it. |
Beta Was this translation helpful? Give feedback.
-
What are the motivating scenarios, things that get easier to do as a result? |
Beta Was this translation helpful? Give feedback.
-
Does anyone know if collection expressions will be permitted within attributes in C#12? I can't find any discussion within the LDM or working group notes but the analyzer IDE0300 ("Collection initialization can be simplified") suggests changing this:
to:
which is currently invalid (CS0182). |
Beta Was this translation helpful? Give feedback.
The limitation is from compiled assembly encoding, not the compile-time constant check. Currently, no collection type can be encoded in constants.
However for attributes we can encode array. Collection expressions may be permitted there.