Issue? More-Derived Extension Method #2579
-
I have this class:
And I call it like so:
When I run the code, the compiler selects ObservableCollection.Add instead of CollectionExtensions.Add. Why is that? I know that ObservableCollection.Add is a valid match but I believe that CollectionExtensions.Add is a better match. |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
IIRC extension methods are not considered alongside instance methods in overload resolution. The compiler will only consider extension methods if there are no instance methods that can be used given the arguments provided. I'd suggest renaming your extension method to |
Beta Was this translation helpful? Give feedback.
-
Extension methods are considered only if there is no valid instance method:
Since |
Beta Was this translation helpful? Give feedback.
-
Thanks @HaloFour ! |
Beta Was this translation helpful? Give feedback.
-
I don't think you can. Collection initializer syntax is designed to enumerate each individual element you want to add to the collection, not a whole bunch at once:
You would have to actually call |
Beta Was this translation helpful? Give feedback.
-
This was very much by design (and effectively mandated by extreme force by the community). People felt it was totally unacceptable (and made that utterly and completely unambiguous when we introduced 'extensions') that an 'extension' would ever get priority over their own types' authored members. If you don't have this, then random extensions added to some namespace you include can now change the behavior of your types and how they were directly authored. |
Beta Was this translation helpful? Give feedback.
IIRC extension methods are not considered alongside instance methods in overload resolution. The compiler will only consider extension methods if there are no instance methods that can be used given the arguments provided.
I'd suggest renaming your extension method to
AddRange
, that is the convention used to add multiple elements to a collection in the BCL.