Is it possible to add more objects of different types to the same list and how do I do it?
I’ve got a base class and three subclasses and I want all the subclass objects in the same list.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Sure – just create a list using the base type as the generic type argument:
Note that when you retrieve the items again, you’ll only “know” about them as the base type though, so you’ll need to cast if you want to perform any subtype-specific operations. For example:
If you want to get all the elements of a particular type (or subtype thereof) you can use the
OfType<>method: