How to implement a private setter when using the interface?

I created an interface with some properties.

If the interface does not exist, all properties of the class object will be set to

{ get; private set; } 

However, this is not allowed when using the interface, so is it possible to do this, and if so, how?

+123
c # interface getter-setter
Aug 15 '13 at 9:35 on
source share
2 answers

In the interface you can only define getter for your property

 interface IFoo { string Name { get; } } 

However, in your class, you can extend it to have a private setter -

 class Foo : IFoo { public string Name { get; private set; } } 
+236
Aug 15 '13 at 9:37 on
source share

The interface defines an open API. If the public API contains only getter, then you define only getter in the interface:

 public interface IBar { int Foo { get; } } 

The private setter is not part of the public api (like any other private member), so you cannot define it in the interface. But you can add any (private) members to the implementation of the interface. In fact, it does not matter if the setter is implemented as open or closed, or if there will be a setter:

  public int Foo { get; set; } // public public int Foo { get; private set; } // private public int Foo { get { return _foo; } // no setter } public void Poop(); // this member also not part of interface 

The setter is not part of the interface, so it cannot be called through your interface:

  IBar bar = new Bar(); bar.Foo = 42; // will not work thus setter is not defined in interface bar.Poop(); // will not work thus Poop is not defined in interface 
+25
Aug 15 '13 at 9:38 on
source share



All Articles