Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

interface

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?

like image 554
bfops Avatar asked Jul 16 '26 18:07

bfops


2 Answers

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; }
like image 145
Stewart_R Avatar answered Jul 18 '26 07:07

Stewart_R


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.

like image 36
Leandro Avatar answered Jul 18 '26 06:07

Leandro