Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IComparable magic - why it's a valid statement?

Tags:

c#

.net

I don't understand why it's working ...

class Program
{
    static void Main(string[] args)
    {
        IComparable.Equals(12, 3);
    }
}

The IL code:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       21 (0x15)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldc.i4.s   12
  IL_0003:  box        [mscorlib]System.Int32
  IL_0008:  ldc.i4.3
  IL_0009:  box        [mscorlib]System.Int32
  IL_000e:  call       bool [mscorlib]System.Object::Equals(object,
                                                        object)
  IL_0013:  pop
  IL_0014:  ret
} // end of method Program::Main

It compiles to bool Object.Equals(Object,Object), but why?

like image 675
Balázs Szántó Avatar asked Apr 09 '13 21:04

Balázs Szántó


1 Answers

It compiles to bool Object.Equals(Object,Object), but why?

"Why?" questions are imprecise and difficult to answer, so instead I'll answer a "what?" question.

What section of the C# specification justifies the legality of this strange behaviour?

Section 7.4 of the C# specification says that when you are doing a member lookup of the form T.N

... the set consists of all accessible members named N in T, including inherited members and the accessible members named N in object... [emphasis added]

object.Equals is an accessible member named Equals in object, so it is a candidate.

like image 90
Eric Lippert Avatar answered Sep 18 '22 19:09

Eric Lippert