I had a discussion in another thread, and found out that class methods takes precedence over extension methods with the same name and parameters. This is good as extension metho
I like Jon's answer, but there's another approach similar to Daniel's. If you have a lot of extension methods, you can define a "namespace" of sorts. This works best if you have a stable interface to work from (i.e., if you knew IThirdParty
wasn't going to change). In your case, however, you'd need a wrapper class.
I've done this to add methods for treating strings as file paths. I defined a FileSystemPath
type that wraps a string
and provides properties and methods such as IsAbsolute
and ChangeExtension
.
When defining an "extension namespace," you need to provide a way to enter it and a way to leave it, as such:
// Enter my special namespace
public static MyThirdParty AsMyThirdParty(this ThirdParty source) { ... }
// Leave my special namespace
public static ThirdParty AsThirdParty(this MyThirdParty source) { ... }
The method to "leave" the "namespace" may work better as an instance method instead of an extension method. My FileSystemPath
just has an implicit conversion to string
, but this does not work in all cases.
If you want MyThirdParty
to have all the currently-defined members of ThirdParty
as well as the extension methods (but not future-defined members of ThirdParty
), then you'd have to forward member implementations to the wrapped ThirdParty
object. This can be tedious, but tools like ReSharper can do it semi-automatically.
Final Note: the "As" prefix on entering/leaving the namespace is a sort of unspoken guideline. LINQ uses this system (e.g., AsEnumerable
, AsQueryable
, AsParallel
leave the current "namespace" and enter another one).
I wrote a blog post early this year about what I call "extension-based types." There are more pitfalls than just the inability to override instance methods. However, it is a very interesting concept.