Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting to object in .NET reference source

Tags:

c#

.net

object

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) 
like image 906
afaolek Avatar asked Sep 23 '15 10:09

afaolek


1 Answers

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 
like image 72
Jon Skeet Avatar answered Oct 12 '22 23:10

Jon Skeet