Reputation: 7005
I have and interface as follow:
public interface IData
{
String Name { get; set; }
}
And a 2 classes that implements it:
public class Data1 : IData
{
public String Name { get; set; }
}
public class Data2 : IData
{
public String Name { get; set; }
}
I need to prevent getting the Name of a Data2
instance. The compiler does not allow all following forms:
internal String Name { get; set; }
private String Name { get; set; }
public String Name { private get; set; }
I do understand the logical reason why this is not explicitly possible. Properties will be accessed using the interface which does not have any clue about implemented access modifiers and will fail if it can't find it.
My use case is that both Data1
and Data2
instances should be able to use methods where an IData
parameter is used (some of the methods where no use of Name
exist), but Data2
is sensitive and should not be accessed directly. Therefore I am looking for a workaround.
Upvotes: 1
Views: 579
Reputation: 29981
The compiler doesn't allow the types implementing this interface to change this, because you ask it not to. You defined an interface which has a public getter and setter.
public interface IData
{
String Name { get; set; }
}
It sounds like you need two interfaces:
public interface ISettableData
{
String Name { set; }
}
public interface IData : ISettableData
{
String Name { get; set; }
}
And the implementation:
public class Data1 : IData
{
public String Name { get; set; }
}
public class Data2 : ISettableData
{
public String Name { set; }
}
Upvotes: 2
Reputation: 754575
It sounds like you want the access of Name
through instances of Data2
to be disallowed. If that is the case then use an explicit interface implementation
public class Data2 : IData {
String IData.Name {
get { ... }
set { ... }
}
}
Now Name
will only be accessible when Data2
instances are viewed as IData
Data2 obj = new Data2();
string name = obj.Name; // Error!
IData other = obj;
name = other.Name; // Ok
Upvotes: 5