168

I've created an interface with some properties.

If the interface didn't exist all properties of the class object would be set to

{ get; private set; }

However, this isn't allowed when using an interface,so can this be achieved and if so how?

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
dotnetnoob
  • 10,783
  • 20
  • 57
  • 103

2 Answers2

330

In interface you can define only 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;
    }
}
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
  • 2
    It doesn't seem to complain if the setter is public either even if the interface only contains a getter. – Mike Cheel Jan 31 '18 at 19:18
  • 9
    @MikeCheel Thats because the interface only defines the minimum methods/accessors. You're free to add more for when you're using the object directly. Though when using an object as the interface type only those methods/accessors defined in the interface are useable. – Marcello Nicoletti Feb 26 '18 at 21:40
37

Interface defines public API. If public API contains only getter, then you define only getter in interface:

public interface IBar
{
    int Foo { get; }    
}

Private setter is not part of public api (as any other private member), thus you cannot define it in interface. But you are free to add any (private) members to interface implementation. Actually it does not matter whether setter will be implemented as public or private, or if there will be 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

Setter is not part of interface, so it cannot be called via 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
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459