-
Notifications
You must be signed in to change notification settings - Fork 1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Collection expression loophole: ability to invoke .Add() method with the parameter type not matching the collection expression element type #7724
Comments
This doesn't seem like it should compile. The type of |
I believe this is by-design from current spec. There exists a conversion from |
feels like a spec bug :) |
Moving to csharplang to close the spec bug. |
This should not be supported unless we can find a reasonable use case. Otherwise, It shouldn't be supported for collection expressions. |
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. |
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. |
Perhaps a diagnostic could be reported if the element as converted for the BadCandidateForCollectionExpression zs = [default]; // warning: converting 'default' to 'string' for Add(string) |
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
.The text was updated successfully, but these errors were encountered: