Wednesday, April 02, 2008

C# quiz: 4/?

Given the following code:

    internal class Test {
public int Foo { get; set; }
public int Bar { get; set; }

#if CUSTOM
public override int GetHashCode() {
return Foo.GetHashCode() ^ Bar.GetHashCode();
}

public override bool Equals(object obj) {
if (object.ReferenceEquals(obj, null)) return false;
Test t = obj as Test;
if (t != default(Test)) {
return (Foo == t.Foo) && (Bar == t.Bar);
}
return false;
}
#endif
}

and the following test code:

            Dictionary<Test, string> dict = new Dictionary<Test, string>();
Test foo = new Test { Foo = 1, Bar = 2 };
dict[foo] = "Hello World";
foo.Bar = 42;
if (dict.ContainsKey(foo)) {
Console.WriteLine("it's there");
} else {
Console.WriteLine("it's not");
}

Answer the following questions:



  1. With CUSTOM not defined, what does the test code print?

  2. If CUSTOM is defined, does it change the outcome?

  3. What if Test is changed to a struct and CUSTOM is not defined, what is the output?

  4. If Test is a struct and CUSTOM is defined, what happens?

No comments: