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.
Notes. 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.
Test example. 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.
Tip For each object element, the type information is retained and can be used later. This program creates an array of 2 objects.
Detail We loop over the array, and call GetType and test its result against typeof expressions.
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
---
A discussion. 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.
Usage. 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.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 23, 2023 (edit).