Collection expression loophole: ability to invoke .Add() method with the parameter type not matching the collection expression element type #8920
Replies: 9 comments
-
@cston @333fred to see if this is by design based on our last meetings I don't imagine this is an interesting case to support given that it doesn't behave like any normal collection does. |
Beta Was this translation helpful? Give feedback.
-
This doesn't seem like it should compile. The type of |
Beta Was this translation helpful? Give feedback.
-
I believe this is by-design from current spec. There exists a conversion from |
Beta Was this translation helpful? Give feedback.
-
feels like a spec bug :) |
Beta Was this translation helpful? Give feedback.
-
Moving to csharplang to close the spec bug. |
Beta Was this translation helpful? Give feedback.
-
This should not be supported unless we can find a reasonable use case. Otherwise, It shouldn't be supported for collection expressions. |
Beta Was this translation helpful? Give feedback.
-
A behavior I found a bit amusing here is that if you change the parameter into a float, and you try to pass a float to that method it will complain that it will only allow an int, not a float! If you give it an int however, it will silently pass a float instead. |
Beta Was this translation helpful? Give feedback.
-
There should probably be a check at compile time. It would simply check if the .Add() method has the same type as the IEnumerable. If not, it can't be used in collections expressions. |
Beta Was this translation helpful? Give feedback.
-
Perhaps a diagnostic could be reported if the element as converted for the BadCandidateForCollectionExpression zs = [default]; // warning: converting 'default' to 'string' for Add(string) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Version Used:
main
branchSteps to Reproduce:
Expected Behavior:
Impossible to fill the collection expression, no
Add
method can accept the value ofint
type - the element type inferred as a collection expression element type.Actual Behavior:
If the expression is both convertible to inferred element type and can be accepted by some non-
int
Add
method overload - it compiles successfully.As the result you have a really weird language context - you can only pass expressions that are implicitly convertible to
int
, but the invoked method acceptsstring
value.I guess this is the poorly written check in frontend, I guess instead of checking the element expression to be convertible to
int
you probably must check the parameter type of invoked.Add()
method to have type convertible toint
.Beta Was this translation helpful? Give feedback.
All reactions