Casting to object in .NET reference source

C#.NetObject

C# Problem Overview


I was going through the OperatingSystem.cs file in the .NET reference source and noted this code in line 50:

if ((Object) version == null)

version is an object of class Version, which means version derives from Object. If that is so, isn't it redundant casting to Object? Wouldn't it be the same as this?

if (version == null)

C# Solutions


Solution 1 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionafaolekView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow