Reputation: 561
In a new line of work I have been told to avoid using Extension Methods for Types that you (or your organization) have no control over, meaning external libraries, framework types such as string, list, and others.
The argument I was given is that this will be bad if the framework developer now decides to implement a method that has the same names and/or parameters as your extension method.
While this problem may arise, this argument effectively reduces the usability of extension methods to nearly zero. Would this argument be considered valid? I am not suggesting to use extension methods everywhere, but I would like to know of similar arguments for and against it.
Upvotes: 0
Views: 103
Reputation: 1500665
It's an argument which has some merit, but in lots of cases the problems can be avoided:
If your extension methods have names which would be very unlikely to be added to the external libraries, then practically speaking it's not an issue. For example, if your company writes Frobulators, and that's a term which is specific to you, then writing
public static Frobulator ToFrobulator(this string Frobulator)
really isn't going to be a problem in reality.
Upvotes: 2
Reputation: 156978
Of course, the risk is there, but defining something on closed or sealed
types you have no control over is exactly what extension methods is about. If you'd only create extension methods on types from your own, the effectiveness of extension methods (compared to regular methods) would be minimized.
There is a very easy 'solution' for this in naming conventions. If you'd prefix or postfix your extensions with a specific identifier, you will be sure Microsoft doesn't create a similar method.
Upvotes: 1