class MyBase
{
protected object PropertyOfBase { get; set; }
}
class MyType : MyBase
{
void MyMethod(MyBase parameter)
{
// I am looking for:
object p = parameter.PropertyOfBase; // error CS1540: Cannot access protected member 'MyBase.PropertyOfBase' via a qualifier of type 'MyBase'; the qualifier must be of type 'MyType' (or derived from it)
}
}
Is there a way to get a protected property of a parameter of a type from an extending type without reflection? Since the extending class knows of the property through its base type, it would make sense if possible.
A protected property is only accessible to an instance of a derived class, not to instances of derived classes.
There is a difference and it does make sense, protected members should not give up their value to any other instance, even an instance derived from the same type.
(Edited, got myself a bit tongue tied!)
Last time I faced a similar problem, I used the solution of adding a protected static method to the base:
I think you should ask yourself if there is a better way of doing what you want to do. You want PropertyOfBase to act as public in the context of MyType.MyMethod(), but to be protected in all other situations. Why?
As you are inheriting from MyBase, you can access all fields/properties/methods from it marked as "protected" using the "base" keyword.
No, you can't do this.
You're only allowed to access protected members of objects of the accessing type (or derived from it). Here, we don't know whether the parameter is of type MyType or SomeOtherCompletelyDifferentType.
EDIT: The relevant bit of the C# 3.0 spec is section 3.5.3:
There's a good reason you can't do this. Suppose someone writes:
If the language allowed what you're asking for, you could violate the assumed invariants of
Other
by modifying the value ofPropertyOfBase
.