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?
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With