When you put those two lines nicely together, you will think "of course i can execute methodB()
on that object! It is a B
, obviously!".
But now consider this:
private void DoSomethingWithAnA(A obj1)
{
obj1.MethodB();
}
Why would this work? In this method, you only know that you receive an object A
, nobody will assume that you have to call it with an object B
. After all, if your method wanted to do something with a B
, it should have asked for a B
, not an A
!
Of course, I can call the method with a B
, this would not be a problem:
DoSomethingWithAnA(new B());
But that doesn't mean that DoSomethingWithAnA
all of a sudden will do something with a B
, it just does something with an A
.
If you also want to do something B-specific, you can, however:
private void DoSomething(A obj1)
{
obj1.MethodA();
if (obj1 is B)
{
((B)obj1).MethodB();
}
}
This method would do something with a B
if you pass it a B
. However, it first needs to check if the A
you send is actually also a B
, and then it casts the A
to a B
. On the resulting B
it can then call MethodB()
.