bfops
bfops

Reputation: 5678

Read-only interface property that's read/writeable inside the implementation

I'd like to have an

interface IFoo
{
    string Foo { get; }
}

with an implementation like:

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

I'd like the property to be gettable through the interface, but only writable inside the concrete implementation. What's the cleanest way to do this? Do I need to "manually" implement the getter and setter?

Upvotes: 3

Views: 1804

Answers (4)

Ahmad
Ahmad

Reputation: 9658

Just use protected set and also remove the IFO before the property to make it implicit.

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

Upvotes: 0

Stewart_R
Stewart_R

Reputation: 14485

interface IFoo
{
    string Foo { get; }
}


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

almost as you had it but protected and drop the IFoo. from the property in the class.

I suggest protected assuming you only want it accessable from INSIDE the derived class. If, instead, you'd want it fully public (able to be set outside the class too) just use:

public string Foo { get; set; }

Upvotes: 4

juharr
juharr

Reputation: 32266

Either make the implementation implicit instead of explicit

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

Or add a backing field

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

Upvotes: 2

Leandro
Leandro

Reputation: 1555

Why the explicit implementation of the interface? This compiles and works without problems:

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

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

Upvotes: 2

Related Questions