Use Array methods in C#

[Array methods]

The example Sort and search arrays in C# shows how to use two useful Array methods: Sort and BinarySearch. This example demonstrates some other useful Array methods.

For simplicity, this example uses arrays of characters to demonstrate the Array methods, but those methods work with any kind of array. You could perform some of these operations on the characters more easily if you treat them as strings, but the point of this example is to show how the Array methods work.

Enter a string in the Items RichTextBox at the top of the form and a search character in the Test Item text box. Then click Go to make the program use the following code to demonstrate the Array methods.

private void btnGo_Click(object sender, EventArgs e)
{
    // Clear any previous formatting.
    rchItems.Select(0, rchItems.Text.Length);
    rchItems.SelectionColor = Color.Black;
    rchItems.SelectionBackColor = Color.White;

    // Array.Reverse.
    char[] items = rchItems.Text.ToCharArray();
    Array.Reverse(items);
    txtReverse.Text = new string(items);

    // Array.Sort.
    items = rchItems.Text.ToCharArray();
    Array.Sort(items);
    txtSort.Text = new string(items);

    // Array.IndexOf.
    char test_char = txtTestChar.Text[0];
    items = rchItems.Text.ToCharArray();
    int index_of = Array.IndexOf(items, test_char);
    txtIndexOf.Text = index_of.ToString();
    if (index_of >= 0)
    {
        rchItems.Select(index_of, 1);
        rchItems.SelectionColor = Color.Red;
    }

    // Array.LastIndexOf.
    int last_index_of = Array.LastIndexOf(items, test_char);
    txtLastIndexOf.Text = last_index_of.ToString();
    if (last_index_of >= 0)
    {
        rchItems.Select(last_index_of, 1);
        rchItems.SelectionBackColor = Color.LightBlue;
    }
    rchItems.Select(0, 0);

    // Copy Equals.
    char[] copy = new char[items.Length];
    Array.Copy(items, copy, items.Length);
    txtCopyEquals.Text = Array.Equals(items, copy).ToString();

    // Clone Equals.
    char[] clone = (char[])items.Clone();
    txtCloneEquals.Text = Array.Equals(items, clone).ToString();

    // Two arrays set to indicate the same memory location.
    char[] reference = items;
    txtRefEquals.Text = Array.Equals(items, reference).ToString();

    // Array.Resize.
    int initial_length = items.Length;
    Array.Resize(ref items, 2 * initial_length);
    Array.Copy(items, 0, items, initial_length, initial_length);
    rchLarger.Text = new string(items);

    // Array.Resize.
    Array.Resize(ref items, initial_length / 2);
    rchSmaller.Text = new string(items);
}

The code first removes any formatting from the Items RichTextBox in case you’ve clicked Go before.

The first Array method the code demonstrates is Reverse. The code gets the text that you entered, converts it into an array of char, and stores it in the array items. It then calls Array.Reverse to reverse the items in the array. Notice that this method, and many other Array methods, does not return a value. Instead those methods perform their operations on the array itself. That means if you want to preserve the original array, you must copy it before you call Reverse or the other methods. This example recreates the items array as needed by reading it from the Items RichTextBox.

After it calls Array.Reverse, the code uses the reversed array to initialize a new string and displays it. The result is the original string with its letters arranged backwards.

Next the code uses the Array.Sort method to sort the characters in the items array. It then displays the result.

The code then uses the Array.IndexOf method to find the test character in the items array. This is relatively simple and you’ve probably used IndexOf with strings. This is exactly the same except Array.IndexOf can locate any kind of item in an array. For example, if you have an array of Person objects, it can locate a particular object. Note that the objects must be the same Person objects, not two different objects that happen to have the same property values. The Array.IndexOf method uses reference equality not value equality.

After it finds the index of the target character, the code displays its position and highlights the character in the original string in red.

Similarly the code uses Array.LastIndexOf to find the last instance of the character, displays its location, and highlights it with a light blue background.

Next the code demonstrates the Array.Equals method three times. First it uses Array.Copy to make a copy of the array and then uses Array.Equals to see if the two are equal. Even though both arrays contain the same items, they are not equal (as you can see in the picture). (One way to understand this is to ask yourself what would happen if you set the first entry in one array to X. The entry in that array would change but the entry in the other array would not.)

The code repeats this test with a cloned version of the array. Again the two arrays hold the same items but they are not the same arrays so Array.Equals returns false.

Next the program creates a new variable named reference to refer to an array of char and sets it equal to the items array. Now both reference and items refer to the same array, so Array.Equals returns true. (Now if you set reference[0] to X, items[0] also becomes X because they are two names for the same array.)

The program finishes by resizing the items array twice. First it doubles the length of the array and then uses Array.Copy to copy the first half of the newly resized array (where the original items are) into the second half. It then displays the larger array’s values.

The code then resizes the array so it has half its original size and displays its contents.

In both resize operations, Array.Resize copies whatever items will fit from the original array to the newly resized array. This lets you make an array expandable just like a List does (although probably less efficiently).


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in arrays, classes and tagged , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *