CHAPTER 4 CORE C# PROGRAMMING CONSTRUCTS, PART II
static void DeclareImplicitArrays()
{
Console.WriteLine("=> Implicit Array Initialization.");
// a is really int[].
var a = new[] { 1, 10, 100, 1000 };
Console.WriteLine("a is a: {0}", a.ToString());
// b is really double[].
var b = new[] { 1, 1.5, 2, 2.5 };
Console.WriteLine("b is a: {0}", b.ToString());
// c is really string[].
var c = new[] { "hello", null, "world" };
Console.WriteLine("c is a: {0}", c.ToString());
Console.WriteLine();
}
Of course, just as when you allocate an array using explicit C# syntax, the items in the array’s
initialization list must be of the same underlying type (e.g., all ints, all strings, or all SportsCars). Unlike
what you might be expecting, an implicitly typed local array does not default to System.Object; thus, the
following generates a compile-time error:
// Error! Mixed types!
var d = new[] { 1, "one", 2, "two", false };
Defining an Array of Objects
In most cases, when you define an array, you do so by specifying the explicit type of item that can be
within the array variable. While this seems quite straightforward, there is one notable twist. As you will
come to understand in Chapter 6, System.Object is the ultimate base class to each and every type
(including fundamental data types) in the .NET type system. Given this fact, if you were to define an
array of System.Object data types, the subitems could be anything at all. Consider the following
ArrayOfObjects() method (which again can be invoked from Main() for testing):
static void ArrayOfObjects()
{
Console.WriteLine("=> Array of Objects.");
// An array of objects can be anything at all.
object[] myObjects = new object[4];
myObjects[0] = 10;
myObjects[1] = false;
myObjects[2] = new DateTime(1969, 3, 24);
myObjects[3] = "Form & Void";
foreach (object obj in myObjects)
{
// Print the type and value for each item in array.
Console.WriteLine("Type: {0}, Value: {1}", obj.GetType(), obj);
}
Console.WriteLine();
}
135