Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert from BaseClass<int> to DerivedClass

Tags:

c#

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.

like image 988
zsf222 Avatar asked Jun 18 '26 07:06

zsf222


1 Answers

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
like image 63
Or Yaniv Avatar answered Jun 20 '26 22:06

Or Yaniv