Strongly typed return method interface

I really like being 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(); } 

While in Java I would do it like this:

 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; } 

Note that the Java code indicates the type of instance returned (Pizza instances). C # code does not do this. This bothers me, especially in situations where other programmers do not have access to the source code. Is there any way to fix this?

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

+7
c # ienumerable
source share
1 answer

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(); } 
+15
source share

All Articles