This example program allocates, assigns into, and loops over an object array. It then prints each type of each object in the array.
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
---