deltanovember deltanovember - 3 years ago 184
C# Question

Why can't C# interfaces contain fields?

For example, suppose I want an

interface and that all implementations will contain the field
. Does this mean that every implementation has to separately declare
? Wouldn't it be nicer to simply define this in the interface?

Answer Source

Though many of the other answers are correct at the semantic level, I find it interesting to also approach these sorts of questions from the implementation details level.

An interface can be thought of as a collection of slots, which contain methods. When a class implements an interface, the class is required to tell the runtime how to fill in all the required slots. When you say

interface IFoo { void M(); } 
class Foo : IFoo { public void M() { ... } }

the class says "when you create an instance of me, stuff a reference to Foo.M in the slot for IFoo.M.

Then when you do a call:

IFoo ifoo = new Foo();

the compiler generates code that says "ask the object what method is in the slot for IFoo.M, and call that method.

If an interface is a collection of slots that contain methods, then some of those slots can also contain the get and set methods of a property, the get and set methods of an indexer, and the add and remove methods of an event. But a field is not a method. There's no "slot" associated with a field that you can then "fill in" with a reference to the field location. And therefore, interfaces can define methods, properties, indexers and events, but not fields.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download