25

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.

Ucodia
  • 7,410
  • 11
  • 47
  • 81
  • 4
    Any external code that cares if you have a private setter or no setter at all is most likely badly designed. `private` members are implementation details and thus you should be able to change them freely. – CodesInChaos Oct 14 '11 at 11:39
  • I can't think of a situation where a private setter in an interface would be useful. – CodesInChaos Oct 14 '11 at 11:41
  • 2
    By definition, all members on an interface are public. An interface *is* the public API of an abstraction. – Marc Gravell Oct 14 '11 at 11:48
  • 1
    use protected set, all children would be able to set the value but no external objects – fluf Oct 14 '11 at 12:00
  • +1 public API and +1 for protected set advice. As I commented on FishBasketGordo answer, I forgot about the oriignal goal of interfaces and the frame that comes with it. Thanks everyone. – Ucodia Oct 14 '11 at 12:24

1 Answers1

69

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; }
}
FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
  • 4
    This made me realise that my understanding of interfaces has been deformed with time. I actually forgot about what their original goal really was. I use them as contracts but expects much more from them. Thanks. – Ucodia Oct 14 '11 at 12:22
  • 1
    I googled this because I'm looking for a way to reduce boilerplate in my c#. Interfaces are apparently the recommended workaround to multiple inheritance, but boy does it cause for boilerplate. Specifically I'd like my concrete classes to infer private properties based off the interface so I don't have to declare them at the top of every concrete class. – aaaaaa Aug 29 '17 at 03:52
  • 2
    Concrete classes may also inherit from a base class in addition to implementing zero or more interfaces. Often using a base class has the nice side effect of eliminating some boilerplate. If you think it's worth it, you can build up a small hierarchy of base classes to cover most of your use cases where you'd otherwise want to use multiple inheritance. Beyond that, I would try to use composition rather than inheritance to reduce boilerplate/increase code reuse. – FishBasketGordo Aug 29 '17 at 13:45