Dot Net Perls

Initialize Array Values - C#

by Sam Allen

Problem

Initialize an int array to a single value, such as -1, so that every element is set to that value. You may need to use -1 or another value as a 'default' value. This can be helpful for a lookup table of char or int, interop, or many other usages.

Solution: C# and Repeat

Use LINQ, which provides some very useful methods under the static Enumerable class. These can easily be used to prepopulate arrays or Lists to a certain value. This is perfect and the most graceful solution for our situation.

Question: how can I initialize an array to -1?

Use Enumerable.Repeat and ToArray to contruct an int array to assign to your declared array in one line. C# will use compiler methods to repeat N on each element in the array. This is expression-based programming.

using System.Linq;

class Program
{
    static void Main()
    {
        // Initialize an array of -1 integers.
        int[] negativeOnes = Enumerable.Repeat(-1, 10).ToArray();

        // Initialize an array of ' ' chars.
        char[] spaceChars = Enumerable.Repeat(' ', 5).ToArray();
    }
}
  1. It fills an array with -1 ints.
    Assign the array of ints you want to be filled with repeating -1's and then assign it to the Enumerable.Repeat expresion. The array now contains 10 negative values.
  2. It fills an array with spaces.
    Next up, we see an array of ' ' space characters. This could be used for certain kinds of text processing. This method is similar to some methods in other languages such as Python or Perl.
  3. ToArray is called on each.
    Enumerable.Repeat returns an IEnumerable collection, which we can easily convert to an array with ToArray. If we want to use a List<int>, then we can simply use ToList. That's all you need to do.

Question: does this really work?

Yes. The next block of code is written out by a method that displays each value in the first array 'negativeOnes' above. This illustration helps cement the function of these methods.

-1
-1
-1
-1
-1
-1
-1
-1
-1
-1

Question: can I use foreach or for?

You cannot use foreach, but you can use for. The reason you cannot use foreach is that it uses an enumerator, and you must never modify enumerators while using them [see Collection Was Modified Exception]. This code shows the for loop that does the same thing as the Repeat method.

class Program
{
    static void Main()
    {
        // Initialize an array to -1 with a loop.
        int[] negativeOnes = new int[10];
        for (int i = 0; i < 10; i++)
        {
            negativeOnes[i] = -1;
        }
    }
}

Why is Enumerable better?

It is better because it eliminates syntax and complexity when using the for loop. A programmer can easily mistype an operator or number with the for loop. Sometimes, an infinite loop can even occur if the iterator goes in the wrong direction. Expression-based coding is borrowed from functional languages.

Discussion: initializing arrays

LINQ provides excellent methods for list comprehension, which is what this sort of style is called. It mirrors proven functionality in languages such as Perl, and when used properly will reduce the size of your code, make it less bug-prone, and more understandable.

Dot Net Perls
About
Sitemap
Source code
RSS
Arrays
Sort String Array
List Element Equality
2D Array Use
Count Array Elements
Bind Array to DataSource
Recent
Pi
NGEN Installer Class
List Element Equality
DateTime Tips and Tricks
Remove HTML Tags From String
© 2008 Sam Allen. All rights reserved.