简体   繁体   中英

C# overriding GetHashCode on a string type

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. 

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.

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM