tags:

views:

65

answers:

1

I really enjoy to be able to do this in C# :

IEnumerable GetThePizzas()
{
    yield return new NewYorkStylePizza();
    yield return new SicilianPizza();
    yield return new GreekPizza();
    yield return new ChicagoStylePizza();
    yield return new HawaiianPizza();
}

Whereas in Java I would have done it like that :

Collection<Pizza> getThePizzas()
{
    ArrayList<Pizza> pizzas = new ArrayList<Pizza>();

    pizzas.add(new NewYorkStylePizza());
    pizzas.add(new SicilianPizza());
    pizzas.add(new GreekPizza());
    pizzas.add(new ChicagoStylePizza());
    pizzas.add(new HawaiianPizza());

    return pizzas;
}

Notice that the Java code tells the type of what is returned (Pizza instances). The C# code doesn't. It bugs me, especially in situations where others programmers don't have access to the source code. Is there a way to fix this?

Update: My problem was that I used "System.Collections" instead of "System.Collections.Generic" and therefore I was using the non-generic version of IEnumerable.

+15  A: 

Using the generic version of IEnumerable, IEnumerable<T>, you can just as easily do this:

IEnumerable<Pizza> GetThePizzas()
{
    yield return new NewYorkStylePizza();
    yield return new SicilianPizza();
    yield return new GreekPizza();
    yield return new ChicagoStylePizza();
    yield return new HawaiianPizza();
}
Dave Swersky