C# Object ArrayUse object arrays to store many types of elements. Cast the objects in the arrays to use them.
Object array. 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 int for arrays instead.Casts
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 int.Int, uint
Tip: For each object element, the type information is retained and can be used later. It is not lost.
Allocate: We allocate an object array on the managed heap. Elements are always initialized to null on the managed heap.
Note: The "new object()" is basically an empty object that can't be used for much. This is a valid object.
Finally: WriteArray uses the foreach-loop to iterate over the object array. It tests for null to avoid NullReferenceExceptions.ForeachNullReferenceException
C# program that uses object array
static void Main()
// Allocate an object array.
object array1 = new object;
// - 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 = new object();
array1 = new StringBuilder("Initialized");
array1 = "String literal";
array1 = 3;
array1 = null;
// Use the object array reference as a parameter.
static void WriteArray(object array)
// Loop through the objects in the array.
foreach (object element in array)
if (element != null) // Avoid NullReferenceException
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.String Literal
Null: The null literal is a special-cased reference that is compatible with all reference types.Null
Note: Ints are often stored directly in the evaluation stack. The CLR must use boxing to represent ints as objects with type pointers.
Also: When you use an integer variable in a method body, it does not have a type pointer. But its object representation does.Type
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.DataRowDataTable
And: The Microsoft.Office.Interop.Excel namespace uses object arrays for the same general purpose.Excel
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.Array
© 2007-2020 sam allen. send bug reports to firstname.lastname@example.org.