C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
ForeachNullReferenceExceptionC# program that uses object 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("---");
}
}
}
}
Output
System.Object
System.Object
---
Initialized
System.Text.StringBuilder
---
String literal
System.String
---
3
System.Int32
---
Null: The null literal is a special-cased reference that is compatible with all reference types.
NullNote: 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.
TypeAnd: The Microsoft.Office.Interop.Excel namespace uses object arrays for the same general purpose.
Excel