Tuesday, June 17, 2014

How to avoid the expensive ToList on generic list? Generics' OOPness redux

Have you questioned C# generics’ OOPness? Why is C# is not allowing us to return List<Autobot> to List<ITransformer> despite Autobot and Decepticon is an ITransformer?

This won't compile even Autobot implements ITransformer:



Can fix it with ToList, but it's an expensive operation, as it creates a copy:
public static List<ITransformer> GetTransformers(TransformerType t)
{
    if (t == TransformerType.Autobot)
        return GetAutobots().ToList<ITransformer>();
    else if (t == TransformerType.Decepticon)
        return GetDecepticons().ToList<ITransformer>();
         
    return null;
}   


To cut to the chase, return the List<ConcreteClass> to IEnumerable<Interface>:
public static IEnumerable<ITransformer> GetTransformersOop(TransformerType t)
{
    if (t == TransformerType.Autobot)
        return GetAutobots();
    else if (t == TransformerType.Decepticon)
        return GetDecepticons();
         
    return null;
}

Live code: https://dotnetfiddle.net/K3IcR5

For further information why List<ConcreteClass> is not compatible to List<Interface> even the concrete class implements the interface, read about covariance

No comments:

Post a Comment