Saving different types inside a list?

Related: List of several data types?

I want to know how to store various types of arrays (including system types) inside an array.

The question above describes how to create a list that allows only user classes to be used using interfaces. But what if I need a list that only accepts doubles and strings? What about the doubles and the class I wrote? As for the list that only the class written and the class that someone wrote will take (so I cannot add an interface to a third-party class, I think).

I reviewed using List<object> , but I don't know if this was accepted best practice.

+7
source share
5 answers

You can specify not only custom types. List<int> , List<double> , List<string> will also work. If you need to store mixed types, you need to specify the nearest base class for all types. A List<object> can store an instance of any type.

+4
source

If you're willing to give up type safety, you can use an ArrayList , which was the only way to use the pre generics material list.

You can put some shell code around it to accept only paired and string characters.

+4
source

You can create your own collection in which you implement the Add () method, which accepts only doubles and a string, for example:

 void Add(object toAdd) { if (toAdd is string) // add into inner collection ... ... (same for double) } 

But honestly, I really can’t think that you need a collection that accepts only these two types. You can probably solve the problem differently ...

+2
source

You should create a class

 public class MyClass { public string x {get;set;} public double y{get;set;} } 

Then just create an array of this class. This class can have any types that you want, that the beauty of objects in an object-oriented language.

 public MyClass[] someList=new MyClass[insert_number_of_elements]; 
+1
source

You can also use ?, enter a list of the following type:

 public class MyClass { public string? x {get;set;} public double? y {get;set;} } 

That way you can choose if none, one or both can make a difference.

Or, if you do not like the HasValue / Value functions:

 public class MyClass { public enum EType { String, Double }; EType TypeFilled {get; private set } string _x; public string X { get { return _x; }; set { _x = value; TypeFilled = EType.String; } double y; public double y { get { return _y; }; set { _y = value; TypeFilled = EType.Double; } } 

Thus, the typeFilled property determines what is filled. You can add validation to prevent installation twice, etc.

+1
source

All Articles