Object arrays are versatile. They store elements of different types in a single collection. An object reference can point to any derived type instance.
An object array makes code more complex (due to casting). It also decreases runtime performance. When possible, use types like string
or uint
for arrays instead.
We use an object array to store different types of data in each element location. An object array can store reference types such as string
and value types such as uint
.
GetType
and test its result against typeof
expressions.using System; class Program { static void Main() { var objects = new object[]{ "bird", (uint)50 }; foreach (var item in objects) { // Test types of objects, and get the derived types. if (item.GetType() == typeof(string)) { string temp = (string)item; Console.WriteLine("String: " + temp.ToUpper()); } else if (item.GetType() == typeof(uint)) { uint temp = (uint)item; Console.WriteLine("Uint: " + (temp * 2)); } } } }String: BIRD Uint: 100
This example program allocates, assigns into, and loops over an object array. It then prints each type of each object in the array.
null
on the managed heap.object()
is basically an empty object that can't be used for much. This is a valid object.WriteArray
uses the foreach
-loop to iterate over the object array. It tests for null
to avoid NullReferenceExceptions
.using System; using System.Text; class Program { static void Main() { // // Allocate an object array. // object[] array1 = new object[5]; // // - Put an empty object in the object array. // - Put various object types in the array. // - Put string literal in the array. // - Put an integer constant in the array. // - Put the null literal in the array. // array1[0] = new object(); array1[1] = new StringBuilder("Initialized"); array1[2] = "String literal"; array1[3] = 3; array1[4] = null; // // Use the object array reference as a parameter. // WriteArray(array1); } static void WriteArray(object[] array) { // // Loop through the objects in the array. // foreach (object element in array) { if (element != null) // Avoid NullReferenceException { Console.WriteLine(element.ToString()); Console.WriteLine(element.GetType()); Console.WriteLine("---"); } } } }System.Object System.Object --- Initialized System.Text.StringBuilder --- String literal System.String --- 3 System.Int32 ---
The string
is a reference to the character data stored in the string literal. The int
is a value type, but is stored in a "box" so that it can be used as an object.
null
literal is a special-cased reference that is compatible with all reference types.The System.Data
namespace contains some types that use object arrays, such as DataRow
and DataTable
. The object arrays they use represent elements in a database table.
Object arrays are used to store different types of objects together, while retaining the original type information. We use them in methods that accept many types.