Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing different types inside a list?

Tags:

arrays

c#

Related: A list of multiple data types?

I want to know how to store different array types (including system types) inside an array.

The above question covered how to create a list that will allow only user-defined classes by using interfaces. But what if I want a list that will accept only doubles and strings? What about doubles and a class I wrote? What about a list that will accept only a class a wrote and a class someone else wrote (so I can't add an interface to the 3rd party class, I think).

I considered using List<object>, but I don't know if that's the accepted best practice.

like image 403
Michael0x2a Avatar asked Feb 07 '12 22:02

Michael0x2a


People also ask

How to store multiple types of data in a list?

You can specify not only custom types. List<int>, List<double>, List<string> will works as well. If you need to store mixed types - you need to specify closest base class for all types. In List<object> can be stored instance of any type. Show activity on this post.

How to store different data types in an array in Java?

If we want to store different data types in the array, then we can create an array of type object so if I convert to this in type object then now we are able to store type integer. I am able to store type string, by the following code.

How to store mixed types in list<object>?

If you need to store mixed types - you need to specify closest base class for all types. In List<object> can be stored instance of any type. Show activity on this post. If you are willing to give away type safety you can use an ArrayList, which was the only way to use a list of stuff pre generics.

Can we store different types in an array in C #?

Question: Can we store different types in an array in C#? If so then provide a practical example. Ans: Yes, if we create an object array. Before going further, let's understand this concept with an example.


1 Answers

You can specify not only custom types. List<int>, List<double>, List<string> will works as well. If you need to store mixed types - you need to specify closest base class for all types. In List<object> can be stored instance of any type.

like image 84
Samich Avatar answered Sep 28 '22 08:09

Samich