views:

920

answers:

3

There have been occasions where I would want to override a method in a class with an extension method. Is there any way to do that in C#?

For example:

public static class StringExtension
{
    public static int GetHashCode(this string inStr)
    {
        return MyHash(inStr);
    }
}

A case where I've wanted to do this is to be able to store a hash of a string into a database and have that same value be used by all the classes that use the string class's hash (i.e. Dictionary, etc.) Since the built-in .Net hashing algorithm is not guaranteed to be compatible from one version of the Framework to the next, I want to replace it with my own.

There are other case I've run into where I'd want to override a class method with an extension method as well so it's not just specific to the string class or the GetHashCode method.

I know I could do this with subclassing off an existing class but it would be handy to be able to do it with an extension in a lot of cases.

+13  A: 

No; an extension method never takes priority over an instance method with a suitable signature, and never participates in polymorphism (GetHashCode is a virtual method).

Marc Gravell
+2  A: 

If the method has a different signature, then it can be done -- so in your case: no.

But otherwise you need to use inheritance to do what you are looking for.

Chris Brandsma
A: 

As far as I know the answer is no, because an extension method is not an instance.It's more like an intellisense facility to me that let you call a static method using an instance of a class. I think a solution to your problem can be an interceptor that intercepts the execution of a specific method (e.g. GetHashCode()) and do something else.To use such an interceptor (like the one Castle Project provides) all objects should be instansiated using an object factory (or an IoC container in Castle) so that thier interfaces can be intercepted through a dynamic proxy generated in runtime.(Caslte also lets you intercept virtual members of classes)

Beatles1692