Search code examples
c#.netreflectionicomparable

How can I use "is" to test if a type supports IComparable?


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?


Solution

  • 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