**CORRECTED 8/26/08: Apparently my initial code did not work correctly. This appears to be a widespread mistake, as I found about a dozen other people doing the exact thing I was doing with reference types. Corrected code and the non-working example are below.**
I am tired of writing array initialization code that looks like this:
1: TermVector[] vectors = new TermVector[6];
2: for (int i = 0; i < vectors.Length; i++)
3: {
4: vectors[i] = new TermVector();
5: }
I couldn’t believe that there wasn’t a better way to handle this. It turns out that there is: just use LINQ! Here’s my first try (and the way most forum and blog posts recommend to do it):
1: TermVector[] vectors = Enumerable.Repeat(new TermVector(), 6).ToArray();
Whoa, that’s easy. But there’s a problem! If you check the contents of the array, you’ll notice that it is populated with 6 references to the exact same instance of TermVector! That’s not what I wanted. That’s not what I wanted at all! Let’s try again:
1: TermVector[] vectors = Enumerable.Repeat(0, 6).Select(i => new TermVector()).ToArray();
If you inspect the array, you’ll see that you now have references to 6 different instances instead of 6 references to the same instance. Sweet!