Search code examples
c#interfacegetter-setter

Separate getter and setter declarations


How can I separately declare a getter and a setter for a property?

For exemple, say I want to create the following hierarchy:

interface IReadOnlyFoo
{
    string Value { get; }
}

interface IFoo : IReadOnlyFoo
{
    string Value { set; }
}

class BasicFoo : IFoo
{
    string Value { get; set; }
}

The compiler is compaining because IFoo.Value is hiding IReadOnlyFoo.Value, which is not what I want to do. I want to "merge" the getter and setter declarations.

I've had a look at how the .NET Framwork declares the IReadOnlyList and IList interfaces, but it's done in a different way.

How could I acheive what I want to do ? Can I do that with a property or do I really have to create separate GetValue() and SetValue() methods instead?


Solution

  • When you change your interface definition to

    interface IReadOnlyFoo
    {
        string Value { get;  }
    }
    
    interface IReadWriteFoo
    {
        string Value { get; set; }
    }
    
    class BasicFoo : IFoo, IReadOnlyFoo
    {
        public string Value { get; set; }
    }
    

    it should work.