A read-only interface property that is read / written within the implementation

I would like to have

interface IFoo
{
    string Foo { get; }
}

      

with an implementation like:

abstract class Bar : IFoo
{
    string IFoo.Foo { get; private set; }
}

      

I would like the property to be accessed via an interface, but is only writable within a specific implementation. What's the cleanest way to do this? Do I need to "manually" implement the receiver and setter?

+3


source to share


4 answers


interface IFoo
{
    string Foo { get; }
}


abstract class Bar : IFoo
{
    public string Foo { get; protected set; }
}

      

just like yours, but protected

also drop IFoo.

from the class property.



I suggest protected

that you assume that you only want it to be accessible from the INSIDE of the derived class. If instead you want it to be completely public (can be set outside of the class), just use:

public string Foo { get; set; }

      

+4


source


Why explicit interface implementation? This compiles and works without issue:

interface IFoo { string Foo { get; } }
abstract class Bar : IFoo { public string Foo { get; protected set; } }

      



Otherwise, you can have a protected / private property for the class and implement the interface explicitly, but delegate the getter to the getter class.

+2


source


Either make the implementation implicit instead of explicit

abstract class Bar : IFoo
{
    public string Foo { get; protected set; }
}

      

Or add a support field

abstract class Bar : IFoo
{
    protected string _foo;
    string IFoo.Foo { get { return _foo; } }
}

      

+2


source


Just use protected set

and also remove IFO

in front of the property to make it implicit.

interface IFoo
{
    string Foo { get; }
}
abstract class Bar : IFoo
{
    public string Foo { get; protected set; }
}

      

0


source







All Articles