#126 – Initializing Arrays of Reference-Type Objects

You can also use an array initialization expression to initialize an array of objects that belong to a reference type.

For example, if you have a Book class with a constructor that takes three arguments, you can initialize an array of books this way:

 Book[] books = { new Book("Moby Dick", "Melville", "Herman"),
                  new Book("Ulysses", "Joyce", "James"),
                  new Book("The Great Gatsby", "Fitzgerald", "F. Scott")};
Advertisement

#125 – Initializing Multidimensional Arrays

A multidimensional array can also be initialized at the time that it is declared and instantiated, using an array initialization expression.

 byte[,] fourRGBValues = new byte[4, 3] { {0, 255, 0},
                                          {255, 0, 0},
                                          {0, 0, 255},
                                          {255, 255, 255} };

As with one-dimensional arrays, you can leave off the array sizes after the new operator because the size of the new array can be inferred.

 byte[,] fourRGBValues = new byte[,] { {0, 255, 0},
                                       {255, 0, 0},
                                       {0, 0, 255},
                                       {255, 255, 255} };

You can even leave off the new operator entirely.

 byte[,] fourRGBValues = { {0, 255, 0},
                           {255, 0, 0},
                           {0, 0, 255},
                           {255, 255, 255} };

#124 – Declaring and Instantiating Multidimensional Arrays

C# allows declaring arrays of more than one dimension.  Where a 1-dimensional array can be thought of as a simple list of elements, a 2-dimensional array can be thought of as a collection of elements organized into rows and columns.

Here are a couple of examples (remember that all arrays are 0-based):

 // 2-dimensional array
 int[,] hourlyTempsForWeek = new int[7, 24];
 hourlyTempsForWeek[2, 12] = 45;     // Tuesday, 12PM
 hourlyTempsForWeek[6, 23] = 30;     // Saturday, 11PM

 // 3-dimensional array, R/G/B values for each pixel on screen
 byte[, ,] pixelRGBValues = new byte[1024, 768, 3];
 pixelRGBValues[0, 0, 0] = 255;  // R value at (0,0)
 pixelRGBValues[0, 0, 1] = 0;    // G value at (0,0)
 pixelRGBValues[0, 0, 2] = 255;  // B value at (0,0)

#123 – Storing Arbitrary Objects in an Array

Although every element in an array must be the same type, there’s a little trick that you can use to store items of different types.  Since every other type inherits from System.Object (or object), you can declare the array to be of type object and then store any object in it.

Here’s an example of a 5-element array of object, in which we store some value types, an enum and a couple custom types.

 object[] things = new object[5];

 things[0] = 12;             // int
 things[1] = 45.6f;          // float
 things[2] = Moods.Cranky;   // enum Moods
 things[3] = new Person();   // custom types
 things[4] = new Cat();

If you examine the array in the debugger, you’ll see each element is an object, but also a more specific type.

#122 – Arrays Can Contain Any Type of Object

C# arrays can be declared to contain any type of object, as long as all objects in the array are of the same type.

Here are some examples:

 // Arrays of fundamental types
 int[] numbers = new int[4];
 float[] morenums = { 1.1f, 2.2f };

 // Array of enum   (enum Moods { Cranky, Fearful, Wary };)
 Moods[] hourlyMoods = new Moods[24];

 // Array of object instances
 Person[] family = new Person[7];

Person bob = family[2];    // Reference one element

#121 – Array Initialization

You can optionally initialize an array at the time that you declare and instantiate it.  You do this by including an array initialization expression.

 int[] numbers = new int[] { 10, 20, 30, 40 };

You can be even more concise and dispense with the new int[] part.

 int[] numbers = { 10, 20, 30, 40 };

#120 – Array Declaration and Instantiation

Three are three steps in declaring and using arrays in C#–declaration, instantiation and (optionally) initialization.

You start by declaring the array.

 int[] numbers;

At this point, the array has been declared but not instantiated.  We’ve declared a variable that references an array of integers, but no array has been created yet and the value of the variable is still null.

The next step is to instantiate the array.  We create the array of integers, assign memory for it, and set the variable to reference the newly created array.

 numbers = new int[4];    //  Instantiate

At this point, the array exists, but its elements all have default values.  For integer values, this default is 0.

We could declare and instantiate the array at the same time:

 int[] numbers = new int[4];    //  Declare / Instantiate

 

#119 – Arrays

An array in C# is a type that contains a list of items of the same type.  Elements in the list can be referenced by a single variable name and a numerical index.  The first element is accessed using an index value of 0.

For example, below we define a four element array of integer (int) and set its elements to some hard-coded values.

 int[] numbers = new int[4];    //  Declare/create 4-element array of int

 // Set 4 elements to integer values
 numbers[0] = 10;    // 1st element
 numbers[1] = 20;
 numbers[2] = 30;
 numbers[3] = 40;

#118 – Disabling Specific Compiler Warnings

There are times when you knowingly want to include C# code in your program that generates a warning.

For example, the following code will generate a warning at compile time:

 static void Main(string[] args)
 {
     uint x = 0x1234;
 }

The warning appears in the Output window – CS0219: The variable ‘x’ is assigned but its value is never used.

If you’re aware of what this warning means, you don’t intend to change the source code to resolve it, and you want to no longer see the warning for this particular line, you can use the #pragma warning directive.  Place the directive immediately above the offending line and reference warning #219.

 static void Main(string[] args)
 {
#pragma warning disable 219
     uint x = 0x1234;
 }

You’ll no longer get warning #219 for this line when you compile.

#117 – Use #define to Define a Symbol

In addition to defining symbols by specifying them in the project properties dialog (“conditional compilation symbols”), you can define symbols directly in your code using the #define directive.  This is helpful when you want to have a conditional compilation symbol appear in some files, but not throughout the entire project.

Here’s an example.  Note that the #define must be the first thing in the file.

#define LOGGING

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

#if LOGGING
            DoSomeLogging();
#endif
            uint x = 0x1234;
        }
    }
}