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.
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.
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.
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.
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.
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.
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