Laban wrote:
I have a class A which contains a protected member M that I would like to
access. If I derive my own class B from A, I can access M from within the
class, and also expose it via a property. The problem is that an instance
of B cannot be used where an instance of A is expected (unsafe cast), so
it does not solve my problem. Of course I can write a soution that does
not need access to M, but I am trying to find out if there are other
alternatives.
Could anyone give me some recommendations for situations like the above?
Well, protected members are made protected because it's a design decision
that they should NOT be available to outside classes. So probably, if you
find yourself needing that kind of access, there's either something wrong
with the class design or you are doing something that the class designer
didn't want you to do. You should find out why there's this
incompatibility between the class design and your needs and fix it, not
work around it.
That said, of course you can use an instance of a derived class where a
base class instance is expected. Like here:
class A {
protected int M;
}
class B : A {
public int PublicM { get { return M; } }
}
class C {
public void DoSomething(A a) {
// Now we have an A that may of course be a B in reality
// Doing something with a.PublicM is not immediately
// possible here, I suspect that's what you mean.
}
}
...
B b = new B();
C c = new C();
c.DoSomething(b);
...
As the comment in the method says, if you get an A passed in and you want
to access that new member you introduced in the derived B, you can't
immediately do that because the type of the variable you have is still an
A, not a B. If you actually get all types of objects passed in that are
derived from A, and you want to access the derived class members, you
could start like this:
public void DoSomething(A a) {
B b = a as B;
if (b != null) {
// Now do something with b.PublicM
}
}
If there are various derived types of A that you want to deal with, the
code in that method can consist of loads of if statements... have a look
at the visitor pattern (just search Google) for a way to better deal with
that kind of situation.
Oliver Sturm
--
Expert programming and consulting services available
See
http://www.sturmnet.org (try /blog as well)