Umut Derbentoğlu
Umut Derbentoğlu

Reputation: 1196

Equals Method in Interfaces

As I know, everything derived from object except interfaces in .net. But I noticed that when I press "." after interface name Equals method appears. And when I press F12 for equals method, it directs to equals method in object class. If interfaces are not derived from object class, where is equals method coming from?

Upvotes: 6

Views: 1204

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1502816

From section 13.2 of the C# 4 spec:

Note that the members in class object are not, strictly speaking, members of any interface (§13.2). However, the members in class object are available via member lookup in any interface type (§7.4).

And section 7.4:

  • First, a set of accessible members named N is determined:
    • ...
    • Otherwise, the set consists of all accessible (§3.5) members named N in T, including inherited members and the accessible members named N in object. [...]

And section 7.4.1:

For purposes of member lookup, a type T is considered to have the following base types:

...

• If T is an interface-type, the base types of T are the base interfaces of T and the class type object.

Basically it's a fudge, to let the compiler understand that the members of object will always really be available at execution time, even though they're not really members of the type of the expression involved for interfaces.

Upvotes: 15

Motti Shaked
Motti Shaked

Reputation: 1894

Any type that would implement the interface ultimately derives from object, hence Equals is always defined.

Upvotes: 2

Keith Nicholas
Keith Nicholas

Reputation: 44306

interfaces can only ever be on objects.

Upvotes: 1

Related Questions