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?
source to share
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; }
source to share
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.
source to share