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.
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.
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();
}
}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
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;
}
}
}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.
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.