I cannot implicitly convert from a BaseClass<int> to its DerivedClass. I have the following code:
class BaseClass<T>
{
}
class DerivedClass : BaseClass<int>
{
int blah;
}
However a method foo() that returns a BaseClass<int> object cannot make the following works:
DerivedClass tmp = foo();
Update: the casting DerivedClass tmp = (DerivedClass)foo(); also didn't work.
That is due to the rules of inheritance and upcasting.
let's say we've got class A, and B which is derived from it:
Class A{
}
Class B : A{
}
since B is an A, then you can do
A a = new B();
that is correct, you just look at that B through 'eyes of' A. this is called Upcasting.
yet, A is not a B, so doing that
B b = new A()
is incorrect, b cannot be instantiated as it's parent class.
the way to do this would be like
B b = (B)a;
which is called RTTI or Downcasting . which is usually not recommended in OOP.
hope that helps.
EDIT :
The downcasting example I gave throws an error since that "a" variable, is really an A.
safe Downcasting be like this:
A a = new B(); \\a is a B looking through A, upcasting.
B b = (B)a; \\ this is downcasting, since now I want to use a with his B identity
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With