Why C# compiler does not allows private property setters in interfaces?

Ucodia picture Ucodia · Oct 14, 2011 · Viewed 12.2k times · Source

In certain scenario like a MVVM view-model, I sometimes needs to have private setter as the view-model exposes a state that can only be modified internally.

So is this wrong to need a private setter on an interface? (and I mean not particularly in the described scenario) If not, why does the C# compiler does not allow it?

Thanks.

Answer

FishBasketGordo picture FishBasketGordo · Oct 14, 2011

By definition, an interface is a contract for other code to use, not for private members. However, you can specify read-only properties in interfaces and implement a private setter in the concrete class:

public interface IFoo
{
    string MyReadonlyString { get; }
} 

public class FooImplementation : IFoo
{
    public string MyReadonlyString { get; private set; }
}