Casting to object in .NET reference source

No, it’s not equivalent – because Version overloads the == operator.

The snippet which casts the left operand to Object is equivalent to:

if (Object.ReferenceEquals(version, null))

… rather than calling the operator== implementation in Version. That’s likely to make a nullity check as its first action anyway, but this just bypasses the extra level.

In other cases, this can make a very significant difference. For example:

string original = "foo";
string other = new string(original.ToCharArray());
Console.WriteLine(original == other); // True
Console.WriteLine((object) original == other); // False

Leave a Comment