Reputation: 30893
Let's say I have a class which has a property hiding it's base property and a nested class inside this class. Is it possible to access the base hidden *virtual* property from the nested class?
Here is an example:
class BaseClass
{
protected virtual String SomeProperty {get; set;}
}
class Inherited : BaseClass
{
protected new String SomeProperty {get; set;}
class Nested
{
Inherited parent;
public Nested(Inherited parent)
{
this.parent = parent;
}
public void SomeMethod()
{
//How do I access the SomeProperty which belongs to the BaseClass?
}
}
}
The only solution that I can think of is to add a private method to Inherited class which returns base.SomeProperty
Is there a better solution?
Upvotes: 2
Views: 2364
Reputation: 3972
You could cast your InheritedClass
reference to BaseClass
. Since you hide the base property instead of overriding it, this should do the trick.
public void SomeMethod()
{
BaseClass baseRef = parent;
// do stuff with the base property:
baseRef.SomeProperty = someValue;
}
Edit:
To make this work, the SomeProperty
property of the BaseClass
has to be accessible to the nested class, either by making it internal
(if you don't want to make the property accessible outside the declaring assembly) or protected internal
(if you want to allow overriding in derived classes from other assemblies).
If both options are off limits (ie. when your derived class already is in another assembly), you won't get around declaring a wrapper property.
private string SomeBaseProperty
{
get
{
return base.SomeProperty;
}
set
{
base.SomeProperty = value;
}
}
Upvotes: 5