5

I want to check if a type supports IComparable before sorting it, but I've found that checking if a type supports the IComparable interface using "is" does not always give me the correct answer. For example, typeof(int) is IComparable returns false, even though int does support the IComparable interface.

I note that typeof(int).GetInterfaces() lists IComparable and typeof(int).GetInterface("IComparable") returns the IComparable type, so why does "is" not work as I expect?

  • The `is` specs say it returns true when conversion will not throw an exception. try converting an `int` to `IComparable` and see if does any trouble. – Daniel Jul 31 '11 at 15:13

3 Answers3

10

is works on an instance. When you say typeof(int) is IComparable, then what you are really checking whether the type System.Type implements IComparable, which it does not. To use is, you must use an instance:

bool intIsComparable = 0 is IComparable; // true
driis
  • 161,458
  • 45
  • 265
  • 341
5

The int does support IComparable but the type of int doesn't, that is it, you should check the variable itself not its Type, so:

int foo = 5;
foo is IComparable;//the result is true, but of course it will not be true if you check typeof(foo)
Jalal Said
  • 15,906
  • 7
  • 45
  • 68
2

The is operator expects an instance on the left side:

int i = 1;
if (i is IComparable) ...

Compiles (with a Warning about always being true).

And " typeof(int) is IComparable returns false"

That is because you are asking whether (an instance of) the Type class is IComparable. It is not.

H H
  • 263,252
  • 30
  • 330
  • 514