Why might a System.String object not cache its hash code?

后端 未结 6 1875
无人共我
无人共我 2020-12-09 01:34

A glance at the source code for string.GetHashCode using Reflector reveals the following (for mscorlib.dll version 4.0):

public override unsafe int GetHashCo         


        
6条回答
  •  孤街浪徒
    2020-12-09 01:37

    I may have made a wrong conclusion here, but isn't it true that while the string is immutable in the context of a .NET String object, it's still possible to change the value?

    For instance, if you were so inclined to do this...

    String example = "Hello World";
    
    unsafe
    {
        fixed (char* strPointer = myString) {
            strPointer[1] = 'a';
        }
    } 
    

    ...wouldn't example still represent the same String object, but now with a value that would compute a different value for GetHashCode()? I may be off-base here, but since you could easily (if not pointlessly) do this, that would cause some issues as well.

提交回复
热议问题