On Sun, 24 Aug 2008 17:55:46 -0700, Sin Jeong-hun <ty*******@gmail.com>
wrote:
Is there any way to initialize an array of objects without looping
through each elements?
That depends. What version of .NET are you using? If you have .NET 3.5,
you can use LINQ:
A[] arrayA = Enumerable.Repeat(new A(0), 100).ToArray();
Probably less efficient performance-wise than doing it yourself, but it
does read better.
It might be considered a little awkward, but you can use the
Array.ConvertAll() method for similar purpose:
A[] arrayA = Array.ConvertAll(new A[100], delegate { return new A(0);
});
That's available in .NET 2.0, and maybe almost as efficient as an explicit
loop (there's an extra throw-away array allocated, but otherwise should be
about the same). Not quite as expressive as the LINQ version though.
[...]
void Main()
{
A[] arrayA=new A[100];
//At this point, A[0]~A[99] are all nulls
foreach(A a in arrayA) {a=new A(0); }
}
I've been using that kind of code.
I hope not. :) In that code, "a" is read-only and even if you could
assign to it, it wouldn't change the value in the array, just the variable
"a".
You probably meant:
for (int i = 0; i < arrayA.Length; i++)
{
arrayA[i] = new A(0);
}
Hopefully the LINQ version should work for you. Even if it doesn't, if
the explicit pattern bothers you, it would be relatively easy for you to
write a generic method to do the array initialization for you.
Pete