58

In C#, the following code is valid

interface I{
    int property{get;set;}
}

Which doesn't make any sense to me. This seems to break one of the most important principles of interfaces: lack of state (in other words, no fields). Doesn't the property create an implicit private field? Wouldn't that be really bad for interfaces?

3 Answers3

79

I think the confusing part is that if you write int Property { get; set; } inside a class, then it's an auto-property with implicit backing field.

But if you write exactly the same thing in an interface, then it's not auto-property, it just declares that the property is part of the interface and that any type that implements the interface has to contain that property (as auto-property or not), but it doesn't create the backing field.

One way to see the difference is to write int Property { get; }: this is valid in an interface and declares a property that has only a getter, but no setter. But it won't compile in a class (unless you're using C# 6.0), because auto-property has to have a setter.

svick
  • 10,137
  • 1
  • 39
  • 53
22

Defining the property as you've shown is the same as defining methods int GetProperty() and void SetProperty(int i). Properties are powerful short-hand in C#.

A property does not implicitly create a private field in C#. That is the default implementation of an auto-property, for example public string MyString { get; set;} - however, a property which defines custom logic in the get method does not generate an implicit private field.

Lastly, as interfaces are concerned with public API, what would it matter if the implementation of an interface property relied on a private field - implicit or otherwise? That is hidden from consumers of the interface regardless.

NWard
  • 376
16

Properties are methods! A backing field will be added to the class which implements the interface (either manually or through an auto-property).

Roman Reiner
  • 1,066