Search code examples
c#compiler-construction

How does Compiler allows Cast to Object for IComparable?Even if Object Does not Implement the Interface?


I am bit Curious to know how does the Compiler treats the following code,even though Object does not implement IComparable Interface. In general,If we typecast an interface to an object which does not implement the interface,Compiler will throw an Error.

    object i = 6;
    object r = ((IComparable)i).CompareTo(5);
    Console.WriteLine(r);

The object does not implement the IComparable Interface,but how can be the casting done here,should it not say that Object does not Implement IComparable ?

EDIT:What is the behavior with Nullable Type(Nullable Type Does Not Implement IComparable) ?

int? j = 5;
int result = ((IComparable) j).CompareTo(6); 

Should it not be like :

   int result = ((IComparable) (int) j).CompareTo(6);
//int implements IComparable

Solution

  • i is an int, which does implement IComparable. An object will not change its type regardless of how you reference it.

    Edit: The reason the compiler doesn't give you an error here (had it not been valid, that is) is that since you're casting an object, it cannot know until runtime whether the cast will work.