Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding different object types to a c# 4.0 collection

Tags:

c#-4.0

I have a function that returns objects of different types based on the parameter passed to this function. Is it possible to add these different object types to a collection based on some identifier in C# 4.0? Usually we do something like this List or List but i want one collection which can add object of any type.

like image 649
SharpD Avatar asked Aug 25 '10 08:08

SharpD


People also ask

Can we store different data types in list in C#?

We can use an ArrayList class that is present in the System. Collections namespace,. Using it we can store different types because the ArrayList class operates on the object type.

How do you create an object collection in C#?

You can create a generic collection by using one of the classes in the System. Collections. Generic namespace. A generic collection is useful when every item in the collection has the same data type.

What is object type in C# with example?

Everything in C# is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake. A Class is like an object constructor, or a "blueprint" for creating objects.


1 Answers

Instead of just making a List<object> like other posters are recommending, you may want to define an interface eg IListableObject that contains a few methods that your objects need to implement. This will make any code using these objects much easier to write and will guard against unwanted objects getting into the collection down the line.

like image 51
James Westgate Avatar answered Sep 30 '22 19:09

James Westgate