16.6. Creating and Using an Array of Pointers

Problem

You need to create, initialize, and use an array containing pointers.

Solution

The following code creates three pointers (TheNewBrush1, TheNewBrush2, and TheNewBrush3) that are inserted as elements in an array. The array of pointers to the NewBrush structure is created and set to a size of 3 so that it can hold each NewBrush structure. This newly defined array now contains undefined pointers. These undefined pointers should be initialized either to point to a value or to point to null. Here, all of the pointers in the array are initialized as null pointers. Finally, each NewBrush structure is then added to this array. Now we have a fully initialized array of pointers. From here we can use this array as we wish:

unsafe
{
    NewBrush theNewBrush1 = new NewBrush( );
    NewBrush theNewBrush2 = new NewBrush( );
    NewBrush theNewBrush3 = new NewBrush( );

    NewBrush*[] arrayOfNewBrushPtrs = new NewBrush*[3];
    for (int counter = 0; counter < 3; counter++)
    {
        arrayOfNewBrushPtrs[counter] = null;
    }

    arrayOfNewBrushPtrs[0] = &theNewBrush1;
    arrayOfNewBrushPtrs[1] = &theNewBrush2;
    arrayOfNewBrushPtrs[2] = &theNewBrush3;
}

Notice that the for loop initializes each pointer in the array to null before the array is used. This is usually a good practice so that you do not inadvertently use an uninitialized pointer. Using a pointer that points to null results in a NullReferenceException being thrown on current versions of the CLR. This device makes it easier ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.