0

I got a little conversion problem. Don't think it is very complex but like to know why. Appreciate for your help :D

public class Family<TLivingThing> where TLivingThing : LivingThing
{
    TLivingThing[] members;
}
public abstract class LivingThing
{
    float lifeExpectancy;
}
public class Animal_A : LivingThing{}
public class Animal_B : LivingThing{}

class MainMethod
{
    static void Main()
    {
        LivingThing livingTing = new Animal_A(); // Works great
        Family<LivingThing> familyA = new Family<Animal_A>(); //Got warning
        Family<LivingThing> familyB = (Family<LivingThing>) new Family<Animal_A>(); //Explicit cast warning
    }
}

Got warning: Cannot implicitly convert type 'Family<Animal_A>' to 'Family<LivingThing>'

Explicit cast: Cannot convert type 'Family<Animal_A>' to 'Family<LivingThing>'

May I know why these error occur?

Kevin Sin
  • 13
  • 3
  • Think about the implications for an `IList`. The `IList` interface has an Add method that takes a `T` argument, and a Get method that returns a `T`. If you could cast a `List` to `IList`, can the Add method now accept any `LivingThing`? – Jeremy Lakeman Mar 19 '20 at 04:07
  • Code shown is very confusing and should report very different errors... But presumably you are trying to convert generics of derived class to generics of base class which is asked many times already - i.e. in duplicate I picked to close this post. If that is not what you are asking please [edit] post to provide actual [MCVE] and clarify what you are trying to achieve, – Alexei Levenkov Mar 19 '20 at 04:07
  • @JeremyLakeman I got what you mean. Thank you a lot. – Kevin Sin Mar 19 '20 at 04:21
  • @AlexeiLevenkov Read the old question. It is exactly what I was asking. Sorry for asking a duplicated question. Thank you. – Kevin Sin Mar 19 '20 at 04:23
  • This particular case of asking duplicate question is not exactly problematic as for some reason many people believe that abstract classes are special... hence can't see that it is basic https://www.bing.com/search?q=c%23+generic+base+derived. Question itself shows decent amount of information and enough code (also there is no `TLivingThing` in your code... clearly showing that your have not actually verified that code actually shows the error) for future visitors to match their problem to your post. – Alexei Levenkov Mar 19 '20 at 04:29
  • I have just removed those wrong 'TLivingThing'. Hope it helps :D – Kevin Sin Mar 19 '20 at 04:41

0 Answers0