Sunday, November 17, 2019

Extension methods: what if ...

Say, you have built your own extension method on some .NET-Framework types. However, in the future Microsoft comes up with exact such methods on the specific types itself: Means same method name, same parameter profile (except the this parameter) as your extension method . What happens now?

Here's the answer
  • There will be no compling error at all, I did not even see a compiler warning
  • Visual Studio Intellisense will show you both methods
  • At runtime, the member method on the type is executed - not your extension method

Conclusion
  • Extension methods can exist concurrent to member methods with same profile
  • Extension methods acts as substitude or shadow only

Considerations
  • If you have extension methods which become competetive to member methods, hopefully they do the same, otherwise you will experience quite ugly surprises.
  • If you build extension methods which you assume could became baked into .NET, look out for it's arrival, compare functionality and get rid of your extension method.
  • Name your extension methods correctly and avoid generic names to reduce the risk of running in dilema. Although I don't like to use name prefixes, it really would help.
  • Do not trust reference searches in case extension method and member method exists in competetive situation.

Personal thoughts
I love extension methods. Although I find it quite ugly, that you can compile even with concurrent method situation. I hope future compilers will have an option to complain such situation.