I want to store multiple data type in an array of C# . I researched on this and found one answer. For example: to use object type, the code for which goes like this
object[] array = new object[2];
Is there any other way to achieve this?
I want to store multiple data type in an array of C# . I researched on this and found one answer. For example: to use object type, the code for which goes like this
object[] array = new object[2];
Is there any other way to achieve this?
It depends on the data types you plan on storing in the array.
To store different data types in the same array you must use their common ancestor - object
being the ultimate base class in the .Net framework will enable you to store any data type inside this array.
However, if you are planing on storing types that derive from a more specific base class - you can use that base class.
For instance, if you have an Animal
base class which derived classes are Cat
, Dog
, Tiger
, Snake
and you want to store all of them in an array, you can use an array of Animal
to do that.
Please note that this also applies to interfaces. If you have multiple classes that all are implementing the same interface, you can use an array of that interface. For instance: var myArray = new INotifyPropertyChanged[3];
and inside that array you can put any class implementing that interface.
Instead of Array, you can use ArrayList
to store values with multiple data type.
Something like:
ArrayList a1 = new ArrayList(); //It contains List of object but we can't perform LINQ operations
a1.Add(1);
a1.Add("Example");
a1.Add(true);
More elegant approach would be use of List<Object>
List<Object> a1 = new List<Object>();
a1.Add(1);
a1.Add("Example");
a1.Add(true);
More about Array, ArrayList and List
POC : .net Fiddle