Private set of property in an interface

Asked

Viewed 370 times

8

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

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

This code does not compile, presenting the following message:

Accessibility modifiers may not be used on accessors in an interface

What alternative to ensure the Setter private for this property?

3 answers

10


Interfaces should define public procurement, so it makes no sense to have a private member in it.

At least so far. There are proposals probably for C# 8 interfaces to allow implementations and then it would make sense to have private members, although the name interface starts to lose meaning.

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 the private member will be detail of the interface (in C# 8 there are still limitations in this, but already advanced, who knows more forward has more, has no forecast). You probably have a protected member, then you can do what you want, but there are controversies about using a protected member, even more in an interface, even if it is no longer an interface.

public interface IBar {
    string Id { get; }
}

class Foo : IBar {
    public string Name { get; private set; }
}

I put in the Github for future reference.

6

The safest is you set just get; with this whoever implements the interface will have no option to change the value.

public interface IBar
{
    string Id { get; }
}

Who implement the interface will be able to define its own private set, as shown in that reply. Example:

class Bar: IBar
{
    public string Id
    {
        get;
        private set;
    }
}

5

According to that one answer, you define only the getter of property:

interface IFoo
{
    string Name { get; }
}

And you can extend it in class to have a setter private:

class Foo : IFoo
{
    public string Name
    {
        get;
        private set;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.