Private property set in an interface [duplicate]

6

I'm modeling a C # interface that has a property. However, I want to ensure that all classes that implement this interface keep the setter as private:

public interface IBar
{
    string Id { get; private set; }
}

This code does not compile, with the following message:

  

accessibility modifiers may not be used on accessors in an interface

Which alternative to secure the setter for this property?

    
asked by anonymous 21.08.2017 / 16:28

3 answers

9

Interfaces should define public procurement , so it does not make sense to have a private member in it.

At least until now. There are probably proposals for C # 8 of the interfaces to allow for implementations and then it would make sense to have private members, although the interface name starts to fade.

At the moment you should simply ignore the private member, if private is implementation detail, then let the class decide on this. When the interface behaves like a trait in C # 8 the private member will be interface detail. It will probably have a protected member, there you can do what you are looking for, but there are controversies about using protected member, even more in an interface, even though it is no longer an interface.

public interface IBar {
    string Id { get; }
}

class Foo : IBar {
    public string Name { get; private set; }
}
    
21.08.2017 / 16:35
5

The safest thing is that you set only get ; so anyone who implements the interface will not have the option to change the value.

public interface IBar
{
    string Id { get; }
}

Whoever implements the interface can set their own private set , as shown in this answer . Example:

class Bar: IBar
{
    public string Id
    {
        get;
        private set;
    }
}
    
21.08.2017 / 16:31
4

Second this , you set only getter of the property:

interface IFoo
{
    string Name { get; }
}

And you can extend it in the class to have a private% co:

class Foo : IFoo
{
    public string Name
    {
        get;
        private set;
    }
}
    
21.08.2017 / 16:31