Jan Girke
Jan Girke

Reputation: 156

C# How can I display a list of objects like:

I am trying to display a list of two subclasses of a parent class:

List<Geschenk> GeschenkListe = new List<Geschenk>
{
    new GeschenkKom(1,"PC-Spiel The Moment Of Silence","House Of Tales"),
    new GeschenkKom(2, "PC-Spiel Syndicate", "BullFrog"),
    new GeschenkKom(3, "PC-Spiel Syndicate Wars", "BullFrog"),
    new GeschenkKom(4, "PC-Spiel The Longest Journey", "FunCom"),
    new GeschenkKom(5, "PC-Spiel The Longest Journey: Dreamfall", "FunCom"),
    new GeschenkBas(6, "Weihnachtsstern", 1),
    new GeschenkBas(7, "Etui", 2),
    new GeschenkBas(9, "Weihnachtspyramide", 3),
    new GeschenkBas(10, "Kalender", 1)
};
GeschenkListe.Add(new GeschenkKom(11, "PC-Spiel The Moment Of Silence", "House Of Tales"));

I know what I created but I don't know how it is named correctly or how I can output it. I tried:

foreach(Object f in Geschenkliste)
{
    Geschenkliste(f).Ausgeben();
}

I tried it with Geschenk instead of Object to no avail. Geschenk is the parent class of GeschnekKom and GeschenkBas. Can anybody help me?

Upvotes: 2

Views: 76

Answers (1)

Christos
Christos

Reputation: 53958

You could try this:

foreach(var item in Geschenkliste)
{
    item.Ausgeben();
}

As it can be inferred from your code, you just try to call a method called Ausgeben on each object in the Geschenkliste. So by using the foreach statement like above you can do so. You declare implicitly (using the var keyword) the type of item. At the compile time this would be replaced with Geschenk, which is the type of the items whose references are stored in the list. In other words the above foreach statement is equivalent to the following one:

foreach(Geschenk item in Geschenkliste)
{
    item.Ausgeben();
}

Why by declaring as the type of item the Object class this cannot work?

Because the method Ausgeben is defined on the class Geschenk and not on the System.Object, which is the base class of all types in .NET Framework (Object).

Upvotes: 7

Related Questions