9

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?

Nikola Anusev
  • 6,940
  • 1
  • 30
  • 46

2 Answers2

11

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.

Dan Bryant
  • 27,329
  • 4
  • 56
  • 102
  • 1
    I agree with the side note, though the other way round - an interface with a read-only property, implemented by a class that makes that property writeable -, for which your solution holds as well, is more acceptable and arguably much more common. – O. R. Mapper Aug 12 '13 at 12:13
-2

You can't change the how the interface is implemented in the inheriting class. That is the whole point.. if you need to do something new with a property you could make a new property that references the inherited properties specific implementation. Interfaces are there so you can conform to a specified standard for object inheritance.

UPDATE: On second thought.. you should be able to just do this.... this will compile fine:

public class ModuleScreen : IModuleScreenData
    {
        public string Name { get; set; }
    }
miskiw
  • 94
  • 6
  • I'd like to avoid creating a new property, if possible. Not sure what you mean by changing a way the interface is implemented - I understand that I have to satisfy the contract contained in the interface and explicit implementation certainly is one of the ways to do that. – Nikola Anusev May 14 '13 at 19:50
  • See my update.... you should be able to just add the get and satisfy the interface – miskiw May 14 '13 at 20:02