Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't C# interfaces contain fields?

Tags:

c#

interface

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();
ifoo.M();

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.


Interfaces in C# are intended to define the contract that a class will adhere to - not a particular implementation.

In that spirit, C# interfaces do allow properties to be defined - which the caller must supply an implementation for:

interface ICar
{
    int Year { get; set; }
}

Implementing classes can use auto-properties to simplify implementation, if there's no special logic associated with the property:

class Automobile : ICar
{
    public int Year { get; set; } // automatically implemented
}

Declare it as a property:

interface ICar {
   int Year { get; set; }
}

Eric Lippert nailed it, I'll use a different way to say what he said. All of the members of an interface are virtual and they all need to be overridden by a class that inherits the interface. You don't explicitly write the virtual keyword in the interface declaration, nor use the override keyword in the class, they are implied.

The virtual keyword is implemented in .NET with methods and a so-called v-table, an array of method pointers. The override keyword fills the v-table slot with a different method pointer, overwriting the one produced by the base class. Properties, events and indexers are implemented as methods under the hood. But fields are not. Interfaces can therefore not contain fields.