Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to implement property setter explicitly while having a getter publicly available?

When I define an interface that contains a write-only property:

public interface IModuleScreenData
{
    string Name { set; }
}

and attempt to (naively) implement it explicitly with an intention for the property to also have a publicly available getter:

public class ModuleScreen : IModuleScreenData
{
    string IModuleScreenData.Name { get; set; }
}

then I get the following error:

Error 'IModuleScreenData.Name.get' adds an accessor not found in interface member 'IModuleScreenData.Name'

The error is more or less expected, however, after this alternative syntax:

public class ModuleScreen : IModuleScreenData
{
    public string Name { get; IModuleScreenData.set; }
}

has failed to compile, I suppose that what I am trying to do is not really possible. Am I right, or is there some secret sauce syntax after all?

like image 368
Nikola Anusev Avatar asked May 14 '13 19:05

Nikola Anusev


1 Answers

You can do this:

public class ModuleScreen : IModuleScreenData
{
    string IModuleScreenData.Name
    {
        set { Name = value; }
    }

    public string Name { get; private set; }
}

On a side note, I generally wouldn't recommend set-only properties. A method may work better to express the intention.

like image 157
Dan Bryant Avatar answered Nov 15 '22 20:11

Dan Bryant