You can't, and I agree it's a nuisance, though what I've found myself wanting is not so much what you are looking for, as overriding on the basis of the constraint (so that I could e.g. have a class and a struct version of the same method or class, and have the appropriate one used as applicable).
There are two cases where we can get by well.
One is where our reason for not wanting an extension method to be used is that it's already supplied as an instance method. In fact we get this for free; instance methods are always used instead of extension methods (though a derivedClass.method()
wont' be used when you call baseClass.method()
if it only exists in derivedClass
).
The other case is runtime selection:
public static T SomeMethod<T>(this object value) where T != IEnumerable
{
if(typeof(T).GetInterface("IEnumerable") != null)
{
//behaviour appropriate for IEnumerable
}
else
{
//other behaviour.
}
}
It's not ideal, especially if the only "behaviour appropriate for IEnumerable" is to throw an exception, but it can be enough sometimes.