Search code examples
c#inheritanceinterfaceaccess-modifiersinterface-implementation

How to implement different accessibility modifiers when I implement the interface


I want to create an interface with property which has different accessibility modifiers in derived classes, like:

public interface IPrisoner
{
    string PrisonerName { get; set; }
}

public class Prisoner : IPrisoner
{
    public string PrisonerName { get; private set; }
}

but in this case I get an error:

'Prisoner' does not implement interface member 'IPrisoner.PrisonerName.set'. 'Prisoner.PrisonerName.set' is not public.

How to implement it?


Solution

  • It sounds like you're in control of the interface definition, and can change it. If that's the case, it's as simple as omitting the setter from the property definition on the interface, like so:

    public interface IPrisoner
    {
        string PrisonerName { get; }
    }
    

    This will make the interface only provide a getter. When you implement the interface however, you're free to define the setter using any access modifier you want, so as in your question, you can just implement the interface as follows:

    public class Prisoner : IPrisoner
    {
        public string PrisonerName { get; private set; }
    }
    

    If you define the setter here as public (IE, omit the private access modifier), It still won't make it available over the IPrisoner interface, only references to the concrete Prisoner type will expose it. You can define properties which only have a setter and no getter over an interface in the same way.