what is the correct way for overriding string.GetHashCode()?

220 views Asked by At

I am looking to create a custom string.GetHashCode() method for some of the strings used in a program namespace (as recommended on the string.GetHashCode() msdn page here) Unfortunately the string class is inheritance sealed.

The closest I have gotten is a base class with a string-typed Value accessor, but that will be a little annoying in that the code will read:

CustomStringTypeInstnce.Value.GetHashCode();

instead of the nicer:

CustomStringTypeInstnce.GetHashCode();

that would be possible if the string class were not inheritance sealed. Is the code read I am looking for at all possible?

if not,.. I don't necessarily need to or not need to override the base class string.GetHashCode(), for the entire program namespace but that would work too, how would that be done?

(EDIT) Sorry, got a little attention-tracked, yes, could just use

CustomStringTypeInstnce.GetHashCode();

as suggested by AppDeveloper's answer, I was/am also looking to be able to assign a string to the wrapped string variable directly without having to use an accessor, but I guess that pretty much means using the prohibited inheritance.

2

There are 2 answers

3
Parimal Raj On

i dont think, you can!

String class is sealed for a reason to disallow any such modification.

You can do, expose create Class like

namespace ConsoleApplication2
{

    class MyClass
    {
        private string _state;
        public override int GetHashCode()
        {

            return _state.MyCustomHasCode();
        }
    }
    public static class Program
    {
        public static int MyCustomHasCode(this string str)
        {
            // return "your own hashcode implementation
        }
        static void Main(string[] args)
        {

        }
    }
}
0
Alexei Levenkov On

You can't override String.GetHashCode because it is sealed.

Since the only good usage for GetHashCode is to use for "hash" data structure like Dictionary and HashSet you can instead use constructors that take different IEqualityComparer.

Most common case for strings are covered by StringComparer class. I.e. to have dictionary that compares string in cases insensitive way (ignore culture):

  var ages = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

Note: using GetHashCode for any other purpose (like persisting information about a string instead of SHA256 or other well defined hash) is not recommended. String.GetHashCode documentation explicitly calls out that the results may change from version to version or even between different processes/app domains.

Hash codes for identical strings can differ across versions of the .NET Framework and across platforms (such as 32-bit and 64-bit) for a single version of the .NET Framework. In some cases, they can even differ by application domain