#443 – An Interface Cannot Contain Fields
October 28, 2011 1 Comment
An interface can contain methods, properties, events or indexers. It cannot contain fields.
interface IMoo
{
// Methods
void Moo();
// Field not allowed - compile-time error
string Name;
Instead of a field, you can use a property.
interface IMoo
{
// Methods
void Moo();
// Name as a property is OK
string Name { get; set; }
Interfaces don’t allow fields because they consist of a contract that is a list of methods, whose implementation is provided by a class. Properties are implemented as methods (get and set accessors), so they fit this model. But fields are just data locations, so it doesn’t make sense to include them in an interface.
Another thing interfaces don’t allow and that sometimes confuses new developers: You cannot enforce constructors. This makes perfect sense of course, but it sometimes comes a surprise to people who want a guaranteed Initialize method which an Interface simply cannot provide.