views:

146

answers:

3

I've made the following declaration for interfaces:

public interface IBasic
{
  int Data { get; }
}

public interface IChangeable : IBasic
{
  int Data { set; }
}

The compiler says that IChangeable.Data hides IBasic.Data. It's reasonable. The alternative I've found is:

public interface IBasic
{
  int Data { get; }
}

public interface IChangeable : IBasic
{
  void ChangeData(int value);
}

There is any way to define setter and getters for the same property on different hierarchy on interfaces? Or there are any alternatives to this approach?

+3  A: 

You can re-declare it (or rather, tell the compiler that you intend to hide it):

public interface IChangeable : IBasic
{
  new int Data { set; }
}
class Foo : IChangeable
{
    private int value;
    int IBasic.Data { get { return value; } }
    int IChangeable.Data { set {this.value = value;}  }
}

But this is confusing, and you'll need to use explicit implementations etc, and probably a bit of casting at the caller if you want to use the hidden version. If you went this route, I would recommend exposing both the get and set on IChangeable:

public interface IChangeable : IBasic
{
    new int Data { get;  set; }
}
class Foo : IChangeable
{
    private int value;
    int IBasic.Data { get { return value; } }
    int IChangeable.Data { set { this.value = value; } get {return value; } }
}


Re the comments; to expose on the implementing type:

public interface IChangeable : IBasic
{
    new int Data { set; }
}
public interface IBasic
{
    int Data { get; }
}
class Foo : IChangeable
{
    private int data;
    public int Data {
        get { return data; }
        set { data = value; }
    }
}

This would also work if you make it (which I prefer):

public interface IChangeable : IBasic
{
    new int Data { get; set; }
}
Marc Gravell
In this approach, which is the way to assign value to Foo.Data?
FerranB
`IChangeable c = {some foo}; c.Data = {some value};` You could also put the property on the public API, but it isn't clear from the question whether that would be the `get`, the `set`, both, etc.
Marc Gravell
I want to allow the implementor of `IChangeable` to have the `get` and `set`.
FerranB
+1  A: 

Maybe I've misunderstood your question but wouldn't you just do

public interface IChangeable : IBasic
{
  int Data { get; set; }
}

i.e. Let IChangeable override the property but keep the "get" present.

As IChangeable inherits from IBasic I'm assuming you want an implementation of IChangeable to have an implementation of "get".

d4nt
A: 

I think GetData and SetData methods is more clear for this situation:

public interface IBasic
{  
    int GetData();
}

public interface IChangeable : IBasic
{  
    void SetData(int data)
}
bniwredyc
What about a read only `Data` property with a `SetData` method?
280Z28
2 methods is more clear for me in this case.
bniwredyc