283

For example, suppose I want an ICar interface and that all implementations will contain the field Year. Does this mean that every implementation has to separately declare Year? Wouldn't it be nicer to simply define this in the interface?

3
  • 24
    Interfaces do not have implementation, for this use an abstract class, with the property Year
    – PostMan
    Jan 22, 2010 at 5:08
  • 6
    To add to what's been said here, interfaces are contracts, and a field is an implementation detail in that it defines a slot in the machine's memory to put a value (either scalar or address pointer) into. Jan 22, 2010 at 10:45
  • 10
    But if the field is public, it's part of the contract and not only an implementation detail, right?
    – Alex
    Apr 14, 2016 at 9:23

12 Answers 12

279

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.

11
  • 32
    The one thing I do sometimes miss is a java-like ability to define interface-level constants, which presumably would not require a "slot" to support in the language.
    – LBushkin
    Jan 22, 2010 at 8:54
  • 2
    I like the explanation in simple words. Thanks. "CLR via C#" and "Essential .net volume 1" provide more details. Apr 18, 2011 at 5:40
  • 8
    Why doesnt a field have a slot? and same question with operators? I remember hearing about duck typing using reflection to see if an interface is implemented even if the class did not inherit the interface. Why cant reflection (or a slot) be used to pull up a field? i'm still writing my code so i may not need/want fields but i was surprise to find i cannot use operators. operators are exactly like methods from my understanding except not all can be overloaded (An interface cannot contain constants, fields, operators. From msdn.microsoft.com/en-us/library/ms173156.aspx)
    – user34537
    Apr 24, 2011 at 7:19
  • @acidzombie: The question of why an interface cannot define operators is different (though maybe related) to why it can't contain fields; I'd suggest posting another question if you're still interested in that. Aug 24, 2011 at 12:38
  • 1
    @b1nary.atr0phy why with fields? E.g. if I declared a method int One(), then the implementation public int One(){return 1;} isn't a field.
    – Hi-Angel
    Aug 14, 2015 at 8:20
173

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
}
5
  • 7
    Isn't everything that is public a part of the contract. If a class has public int Year, doesn't it say that the class contract has a field of type Year to be present on it, and accessible?
    – Didier A.
    Mar 10, 2014 at 19:42
  • 3
    Late to the party, but no, in this case it means the contract has a PROPERTY Year which any abiding class is supposed to implement. Properties are actually get/set methods, which have backing field automatically generated if no special logic is needed. Special syntax is just for a clearer notation. Jun 17, 2014 at 12:26
  • How can I define a constant default value (like 123) to that automatic implementation of Year?
    – kungfooman
    Aug 1, 2017 at 1:39
  • 1
    @lama12345 I'm also late to the party, but since C# 6 (2015, .NET Framework 4.6 and .NET Core) you can use an auto-property for that purpose. public int Year => 123;. However, in this case it makes no sense to have a setter, so the interface would have to be defined with int Year { get; }
    – EriF89
    Feb 7, 2020 at 11:35
  • 1
    LBushkin your post must have been marked as the top answer, May 14, 2021 at 6:10
66

Declare it as a property:

interface ICar {
   int Year { get; set; }
}
4
  • 57
    The question is "Why can't C# interfaces contain fields?". This doesn't address that.
    – AakashM
    Jan 22, 2010 at 10:37
  • 23
    I agree that the this answer do not answer the OP question, but well, it solved my problem.
    – user376591
    Jun 7, 2017 at 11:20
  • Why not just int Year;?
    – carloswm85
    Sep 10, 2022 at 15:09
  • @carloswm85 Because that would declare a field in an interface, which the language does not currently allow.
    – Geoff
    Sep 14, 2022 at 7:41
45

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.

3
  • 1
    You provided the technical/actual name (v-table) to the concept of slots mentioned by Eric. Thank you for the detail Hans.
    – RBT
    Feb 1, 2017 at 3:12
  • What would be the point of a v-table if interfaces are disallowed default implementations? This changes in C# 8.0, but that's beside the point.
    – Anthony
    Mar 11, 2020 at 13:11
  • @Anthony Multiple class and struct types can implement the same interface type: so when a method has an interface-typed parameter the compiler (or runtime) needs a way to map each interface member method to an actual implementation function-address in memory, a vtable is a sensible way to achieve that. Another reason is because a derived classes can re-implement an interface (roughly equivalent to overrides for non-interface methods) which would also require a vtable. Only static and non-virtual methods can be entirely resolved statically without vtables (or other techniques).
    – Dai
    Jul 19, 2023 at 12:49
21

Why not just have a Year property, which is perfectly fine?

Interfaces don't contain fields because fields represent a specific implementation of data representation, and exposing them would break encapsulation. Thus having an interface with a field would effectively be coding to an implementation instead of an interface, which is a curious paradox for an interface to have!

For instance, part of your Year specification might require that it be invalid for ICar implementers to allow assignment to a Year which is later than the current year + 1 or before 1900. There's no way to say that if you had exposed Year fields -- far better to use properties instead to do the work here.

21

The short answer is yes, every implementing type will have to create its own backing variable. This is because an interface is analogous to a contract. All it can do is specify particular publicly accessible pieces of code that an implementing type must make available; it cannot contain any code itself.

Consider this scenario using what you suggest:

public interface InterfaceOne
{
    int myBackingVariable;

    int MyProperty { get { return myBackingVariable; } }
}

public interface InterfaceTwo
{
    int myBackingVariable;

    int MyProperty { get { return myBackingVariable; } }
}

public class MyClass : InterfaceOne, InterfaceTwo { }

We have a couple of problems here:

  • Because all members of an interface are--by definition--public, our backing variable is now exposed to anyone using the interface
  • Which myBackingVariable will MyClass use?

The most common approach taken is to declare the interface and a barebones abstract class that implements it. This allows you the flexibility of either inheriting from the abstract class and getting the implementation for free, or explicitly implementing the interface and being allowed to inherit from another class. It works something like this:

public interface IMyInterface
{
    int MyProperty { get; set; }
}

public abstract class MyInterfaceBase : IMyInterface
{
    int myProperty;

    public int MyProperty
    {
        get { return myProperty; }
        set { myProperty = value; }
    }
}
7

Others have given the 'Why', so I'll just add that your interface can define a Control; if you wrap it in a property:

public interface IView {
    Control Year { get; }
}


public Form : IView {
    public Control Year { get { return uxYear; } } //numeric text box or whatever
}
5

A lot has been said already, but to make it simple, here's my take. Interfaces are intended to have method contracts to be implemented by the consumers or classes and not to have fields to store values.

You may argue that then why properties are allowed? So the simple answer is - properties are internally defined as methods only.

1
  • 1
    If you need to access a member just make it a property and you'll be good.
    – Unome
    Sep 2, 2016 at 16:57
3

Interfaces do not contain any implementation.

  1. Define an interface with a property.
  2. Further you can implement that interface in any class and use this class going forward.
  3. If required you can have this property defined as virtual in the class so that you can modify its behaviour.
2

Beginning with C# 8.0, an interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/interface-properties

interface IEmployee
{
    string Name
    {
        get;
        set;
    }

    int Counter
    {
        get;
    }
}

public class Employee : IEmployee
{
    public static int numberOfEmployees;

    private string _name;
    public string Name  // read-write instance property
    {
        get => _name;
        set => _name = value;
    }

    private int _counter;
    public int Counter  // read-only instance property
    {
        get => _counter;
    }

    // constructor
    public Employee() => _counter = ++numberOfEmployees;
}
0

For this you can have a Car base class that implement the year field, and all other implementations can inheritance from it.

0
0

An interface defines public instance properties and methods. Fields are typically private, or at the most protected, internal or protected internal (the term "field" is typically not used for anything public).

As stated by other replies you can define a base class and define a protected property which will be accessible by all inheritors.

One oddity is that an interface can in fact be defined as internal but it limits the usefulness of the interface, and it is typically used to define internal functionality that is not used by other external code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.