0
class Program
{
    static void Main(string[] args)
    {
        new Wtf { Foo = "FOO" }.GetHashCode();
    }

    private struct Wtf
    {
        public string Foo { get; set; }
        public override int GetHashCode() => new { A = Foo }.GetHashCode();
    }
}

If I set a breakpoint here new { A = Foo }.GetHashCode() and open the quickwatch window, the following expressions give different results:

new { A = Foo }.GetHashCode()
this.GetHashCode()

What am I doing wrong?

ConditionRacer
  • 4,418
  • 6
  • 45
  • 67
  • Not really sure about your question, but `new {A = Foo}` is an anonymous object, and `this` points to current class object, both of them would use the `Object.GetHashCode` and it will/could be different – Habib Jun 15 '16 at 20:05
  • @Habib When I hit the breakpoint inside `Wtf.GetHashCode`, `this.GetHashCode` should call `GetHashCode` in the struct, not `Object.GetHashCode` – ConditionRacer Jun 15 '16 at 20:08
  • where is `this.GetHashCode` being called? and your override for `GetHashCode` in the struct will always return a new hash code because you're creating a new anonymous object with each call. you'll need to store the result in a private variable and keep track of it there if you want the same hashcode for every call (which is what is supposed to happen). – ps2goat Jun 15 '16 at 20:43
  • @ps2goat Both expressions are called from the quickwatch window, that's where I'm seeing the discrepancy. The hash's should be the same for both expressions since they are semantically identical, one is just wrapped in another function call. The anonymous object GetHashCode always returns the same hashcode for a given Foo since the GetHashCode algorithm is not random. – ConditionRacer Jun 15 '16 at 20:46
  • @ps2goat No, anonymous objects generate hashcodes based on the constituent values that make up the object: https://msdn.microsoft.com/en-us/library/bb397696.aspx (See the remarks section) "Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashCode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal." – ConditionRacer Jun 15 '16 at 21:15
  • ah, i see that now. but where are you calling 'this'. there must be a breakpoint somewhere when you put that in the watch window, right? – ps2goat Jun 15 '16 at 21:35
  • @ps2goat Yes, I have a breakpoint on `new { A = Foo }.GetHashCode()`, (inside `Wtf.GetHashCode`). When it breaks there, I execute both expressions in the quickwatch window – ConditionRacer Jun 16 '16 at 00:24

0 Answers0