Reputation: 5835
I have the following code:
public class Ancestor
{
public string Property {get; protected set;}
}
public class Base : Ancestor
{
public string Property {get; set;}
}
public class Derived : Base
{
public Derived(string message)
{
//I need both properties to have the message value
}
}
The Ancestor and Base classes are are not my code and I cannot change them.
Is there any way to set the property of the Ancestor the value of message?
Obviously simply doing something like the following won't work
Ancestor ancestor = this;
ancestor.Property = message
because the setter is protected.
Upvotes: 1
Views: 765
Reputation: 5835
I've found a solution that satisfies my needs. My Ancestor class derives from an interface:
public interface IAncestor
{
string Property { get; }
}
What I did was using explicit interface declaration like so:
public class Derived : Base, IAncestor
{
public Derived(string message)
{
Property = message;
base.Property = message;
}
string IAncestor.Property{get { return Property; }}
}
And now the following test passes:
[TestMethod]
public void ValidatePropertyIsFullyPopulated()
{
const string expectedMessage = "hello!";
var derived = new Derived(expectedMessage);
Base baseClass = derived;
IAncestor ancestor = derived;
Assert.AreEqual(expectedMessage, derived.Property);
Assert.AreEqual(expectedMessage, baseClass.Property);
Assert.AreEqual(expectedMessage, ancestor.Property);
//Notice that this Assert WILL fail because Ancestor.Property is
//not marked as virtual.
Ancestor ancestorClass = derived;
//Assert.AreEqual(expectedMessage, ancestorClass.Property);
}
Upvotes: 1
Reputation: 4692
via Reflection only:
public class Derived : Base
{
public Derived(string message)
{
Type type = typeof(Ancestor);
Ancestor a = (Ancestor)this;
type.GetProperty("Property").SetMethod.Invoke(a, new[] { message });
}
}
Upvotes: 3