Home > Software design >  C# Cast inherited class in generic method
C# Cast inherited class in generic method

Time:09-15

I have a generic method called GetOnlyMatchingType() which is supposed to return an array of all the specific inherited classes from an array of classes.

Say you have Apples and Oranges that derive from Fruit. Now say you have a Fruit array and want to get only the Oranges of that array. This is what my method is supposed to do, so you should be able to do:

Fruit.Orange[] oranges = GetOnlyMatchingType<Fruit, Fruit.Orange>(fruits);

Now here is the method:

public static To[] GetOnlyMatchingType<From, To>(From[] from)
{
    int i = 0;
    foreach (From obj in from)
    {
        if (obj is To)
        {
            i  ;
        }
    }

    To[] output = new To[i];
    i = 0;
    foreach (From obj in from)
    {
        if (obj is To)
        {
            output[i] = (To)obj;
            i  ;
        }
    }
    return output;
}

Problem lies in line 18 output[i] = (T)obj;: CS0030: Cannot convert type 'From' to 'To'

I tried replacing every To with From.To but that just gives me compilation errors. Is there any way I can make my method work?

CodePudding user response:

You can just use Enumerable.OfType<T>() instead:

Fruit.Orange[] oranges = fruits.OfType<Fruit.Orange>().ToArray();

But if you really want to use your own home grown version, you need to tell the compiler that To inherits from From for that cast to be valid:

public static To[] GetOnlyMatchingType<From, To>(From[] from) where To : From
  • Related