I was reading about extension methods in C# 3.0. The text I'm reading implies that an extension method with the same signature as a method in the class being extended would be second in order of execution - that is, the method in the sealed class gets called. If this is the case, how can you extend the sealed class ?
2 Answers
Indeed, the actual method takes precedence over the extension method. And just to make it clear - "order of execution" suggests both might be called; only the original method will be invoked. Perhaps pick another name / signature; you can't use extension methods to monkey-patch, if that is your intent.
If there is some base-class / interface (that the type implements) that doesn't have this method, you could perhaps cast it to there...?

- 1,026,079
- 266
- 2,566
- 2,900
-
2HA HA! Monkey-patch...that's a new one. Ok, thanks, I was thinking that if I was correct it would be breaking sealed and that would defeat the whole point of using sealed. – Scott Davies Feb 23 '10 at 18:41
-
1@Scott - also known as duck-punching. I kid you not. – Marc Gravell Feb 23 '10 at 19:24
-
Monkey-patch ... I'm adding that one to my programmer vocabulary. +1 – Yogi Mar 21 '20 at 19:04
Use another method signature. Extension methods imply that you are extending the sealed class with new functionality and not overriding the ones already implemented.
Extension methods have "hide-by-name" semantics with instance members on a type. This means that any accessible instance member on a type will always shadow any extension methods with the same name, even if the extension method is a better fit. As a result, if an instance member is ever added to a type with the same name as an extension method, then the extension method can be rendered uncallable.
For more details, take a look at this post: Extension Methods Best Practices (Extension Methods Part 6)

- 100,159
- 46
- 371
- 480
-
1If you have to call the extension method with the same signature, you can call it explicitly not from the instance. `ExtensionClass.ExtendMethod(instance)` – joe Apr 19 '21 at 02:00