C# – Why C# Allows Properties in Interfaces

cinterfacesproperties

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?

Best Answer

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.

Related Topic