-6

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?

Kobi
  • 135,331
  • 41
  • 252
  • 292
  • 1
    Why do you want to do with it? What are you trying to achieve by storing different basic types in an array ? – Fabjan Jan 31 '19 at 08:59
  • @Apoorva Asthana what is the Inheritance tree of your objects? You can set up an array of something more specific then the object object. – Nexaspx Jan 31 '19 at 08:59

2 Answers2

4

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.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
2

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

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44