C# Type Comparison: Type.Equals vs operator ==

Metro Smurf picture Metro Smurf · Feb 10, 2012 · Viewed 33.3k times · Source

ReSharper suggests that the following be changed from:

Type foo = typeof( Foo );
Type bar = typeof( Bar );

if( foo.Equals( bar ) ) { ... }

To:

if( foo == bar ) { ... }

operator ==

// Summary:
//     Indicates whether two System.Type objects are equal.
//
// Parameters:
//   left:
//     The first object to compare.
//
//   right:
//     The second object to compare.
//
// Returns:
//     true if left is equal to right; otherwise, false.
public static bool operator ==( Type left, Type right );

Equals( Type o )

// Summary:
//     Determines if the underlying system type of the current System.Type is the
//     same as the underlying system type of the specified System.Type.
//
// Parameters:
//   o:
//     The System.Type whose underlying system type is to be compared with the underlying
//     system type of the current System.Type.
//
// Returns:
//     true if the underlying system type of o is the same as the underlying system
//     type of the current System.Type; otherwise, false.
public virtual bool Equals( Type o );

Question
Why would operator == be recommended over Equals( Type o ) when comparing Types?

Answer

Julien Lebosquain picture Julien Lebosquain · Feb 13, 2012

I suggest that you read the excellent When is a Type not a Type? blog post by Brad Wilson. To summarize: a runtime type (represented by the internal type RuntimeType), managed by the CLR, is not always the same as a Type, which can be extended. Equals will check the underlying system type, whereas == will check the type itself.

A simple example:

Type type = new TypeDelegator(typeof(int));
Console.WriteLine(type.Equals(typeof(int))); // Prints True
Console.WriteLine(type == typeof(int));      // Prints False