[OT] Generics and Interfaces

[OT] Generics and Interfaces

Old forum URL: forums.lhotka.net/forums/t/4318.aspx


Patrick.Roeper posted on Friday, February 08, 2008

The past couple of days I have been trying to do some creative things with interfaces and my csla business objects. I've managed to understand... a) creativity gives me a headache & b) I don't understand generics/interfaces as well as I thought...

I've tried to read through some articles in blogs but the examples are a little larger than what I am looking for. Below is a sample program that is modeling the consumption of fruit:

class Program
    {
        interface IFruit { }
        class Apple : IFruit { }
        class Orange : IFruit { }
        class Apples : List<Apple> { }

        static void EatFruit(List<IFruit> fruit)
        {
        }

        static void EatFruit2<T>(List<T> fruit) where T : IFruit
        {
        }

        static void Main()
        {
            EatFruit(new Apples()); // This doesn't work
            EatFruit2(new Apples()); // This does
        }
    }


Can someone explain why the first eat fruit method doesn't work? I understand why the second method works but I'm not seeing why the first method isn't really doing the same thing.

Thanks in advance.

FatPigeon replied on Friday, February 08, 2008

I think the way to look at it is that List<Apple> and List<IFruit> both descend directly from System.Object. Neither descends from the other which would 
need to be the case for EatFruit to work.
The fact is List<Apple> can contain only apples where as List<IFruit> can contain apples or oranges. A List<Apples> can never be a List<IFruit> because it cannot contain oranges and List<IFruit> can never be a List<Apple> because it can contain oranges.
 
The parameter type in EatFruit2 is being defined as List<Apple> by the caller so this does work.
 
Hope this helps.
 
Regards,
 
Patrick
 

Patrick.Roeper replied on Friday, February 08, 2008

That actually makes a lot of sense. Thanks Smile [:)]


Copyright (c) Marimer LLC