Search code examples
c#propertieslanguage-featuresexplicit-implementation

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?


Solution

  • 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.