简体   繁体   中英

How == operator works with System.Type

typeof(int) == typeof(int)

How this expression evaluates ??

When i use

Console.WriteLine(typeof(int));

it outputs System.Int32 using ToString() method of object. So i am assuming that in this expression

 typeof(int) == typeof(int)

ToString() converts both to System.Int32 and then thier string gets compared. Is that true ??

Or something else happenning

No. Like every other class usually does, it uses equality comparer ( == ) System.Type has overridden and the Equals method on one of the two instances to check their equality.

typeof(int) returns a Type , so Type.Equals is called. You can see the source here .

You will see it eventually uses this to compare the two instances:

return (Object.ReferenceEquals(this.UnderlyingSystemType, o.UnderlyingSystemType));

The typeof() operator resolves to a System.Type , and the == operator on System.Type checks reference equality . This is enough for System.Type , because of this guarantee:

A Type object that represents a type is unique; that is, two Type object references refer to the same object if and only if they represent the same type. This allows for comparison of Type objects using reference equality.

http://msdn.microsoft.com/en-us/library/42892f65.aspx

So the answer is, the == checks whether the two types refer to the exact same object in memory, and if the original objects are of the same type, their types are guaranteed to refer to the same object in memory because of the above quote.

The IL code for typeof(int) == typeof(int) is

IL_0000:  ldtoken     System.Int32
IL_0005:  call        System.Type.GetTypeFromHandle
IL_000A:  ldtoken     System.Int32
IL_000F:  call        System.Type.GetTypeFromHandle
IL_0014:  call        System.Type.op_Equality

You can see that it calls the static equality operator

public static bool operator ==(Type left, Type right)

We can't see what this method does in the reference source because apparently it's an external method, but my guess is it either calls the Equals method or performs a similar comparison in native code.

The fact that Console.WriteLine(object); prints out a string doesn't mean the Type type is always a string, similar to how you can print out an int value without said int being viewed and compared via its ToString method.

The == operator will test equality of the types, and in no way touches ToString() .

I think you're getting a bit confused--if I had to guess--on the differentiation between printing something and holding it in memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM