Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do interfaces derive from System.Object? C# spec says yes, Eric says no, reality says no

Tags:

c#

.net

Question is simple and asked in the title.

C# 4.0 Specification says: (§4.2.2)

The object class type is the ultimate base class of all other types. Every type in C# directly or indirectly derives from the object class type.

Eric Lippert says:

Interface types, not being classes, are not derived from object.

Reality says:

Type t = typeof(ICloneable).BaseType; Console.WriteLine(t == null); 

True

So is spec wrong or what? Whom to believe?

like image 244
Andrey Avatar asked Jul 13 '10 10:07

Andrey


Video Answer


1 Answers

It's not quite as simple a question as you might think :)

Interfaces don't derive from object but you can call the members of object on them. So you can call ToString() on an expression which has a compile-time type of IDisposable, for example.

Coincidentally, I overhead a conversation between Neal Gafter and Eric at NDC discussing exactly this point...

I believe section 4.2.2 of the spec is over simplified, unfortunately. Hopefully Mads and Eric will fix it up for a future release - I'll mail them to make sure they see this question.

I'm also struggling to find anything in the spec to back up the rest of this answer. Section 3.4.5 of the C# 4 spec comes as close as I can find:

The members of an interface are the members declared in the interface and in all base interfaces of the interface. 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).

The conversion from an interface type to object is covered by section 6.1.6:

The implicit reference conversions are:

  • From any reference-type to object and dynamic.
like image 182
Jon Skeet Avatar answered Oct 14 '22 10:10

Jon Skeet