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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With