#123 – Storing Arbitrary Objects in an Array

Although every element in an array must be the same type, there’s a little trick that you can use to store items of different types.  Since every other type inherits from System.Object (or object), you can declare the array to be of type object and then store any object in it.

Here’s an example of a 5-element array of object, in which we store some value types, an enum and a couple custom types.

 object[] things = new object[5];

 things[0] = 12;             // int
 things[1] = 45.6f;          // float
 things[2] = Moods.Cranky;   // enum Moods
 things[3] = new Person();   // custom types
 things[4] = new Cat();

If you examine the array in the debugger, you’ll see each element is an object, but also a more specific type.

Advertisement