#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: