c# - Identifying derived types from a list of base class objects -


this may seem kind of "homework-ish" and/or trivial, real business purpose; it's easiest way think of explain i'm conceptually trying do.

suppose have animal class, , other classes (bird, cat, kangaroo). each of these inherits animal.

animal might this:

public class animal {     public animal()     {      }      public string name { get; set; }     public string animaltype { get; set; }     public list<animal> friends { get; set; } } 

kangaroo might this:

public class kangaroo : animal {     public kangaroo()     {      }      public int taillengthinches { get; set; } } 

suppose kangaroo has 2 friends, bird , cat. how add list of "animal" friends (as type animal), preserve ability access properties of derived classes? (as in, still need able work properties specific type of animal, feathercolor bird, example, though considered "animals".

the reason trying when later list of animal's "friends", vital know type of animal friend is. depending on animal type (whether bird, cat, etc) want different (show different template in on asp.net page, actually, don't need specifically).

i guess boils down this...if have list of animal, how know derived type each of objects in list, can cast them derived type or else allows me specific, different properties on each derived type?

thanks!

you can use linq filter on type you're looking for

animals.friends = new list<animal> { new kangaroo(), new bird() }; foreach ( var kangaroo in animals.friends.oftype<kangaroo>()) {   kangaroo.hop(); } 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -