0

Is it possible to override the GetHashCode method for a string, int, int32 etc..

I dont want to create a new object or class and override it that away. I wonder if there was a way to override the type's method. Similar to an extension but not really.

string myString = "sometext";
myString.GetHashCode(); -- I want to override this method. 
2
  • 4
    I have just one question: Why? Commented Jun 26, 2012 at 14:03
  • 1
    No, sorry you cant override a method without inheriting from a base class and string and structs can not be inherited from. Commented Jun 26, 2012 at 14:09

3 Answers 3

2

No, you cannot. Even if you added an extension method, if there is an instance method and an extension method with the same signature being called then the instance method wins. You also can't extend string or int because they're sealed. The best you'd be able to do is create an entirely new class/struct with a string/int property that overrides GetHashCode with your own implementation (you could provide implicit conversions to string or int as well if you wanted.

Sign up to request clarification or add additional context in comments.

Comments

1

If you do not want to create your own class, then no because an override is only possible within a subclass.

An alternative would be to create a custom extension method like:

public static class MyExtensions
{
    public static int GetHashCode2(this string s)
    { 
         // Implementation
    }
}

This would have a similar effect, but you would need to call .GetHashCode2() rather than .GetHashCode()

Comments

1

I think you can only do it if it's in another class [http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overriden-in-c]

Plus, I don't think you'd want to overwrite it globally because there is a strong likely hood that other things will be using that base GetHashCode()

Finally, ask yourself "Why do you want to do this?" If you don't have a really good reason, you don't need to do it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.