.NET offers a generic list container whose performance is almost identical (see Performance of Arrays vs. Lists question). However they are quite different in initialization
I can't say I need this very often - could you give more details as to why you want this? I'd probably put it as a static method in a helper class:
public static class Lists
{
public static List RepeatedDefault(int count)
{
return Repeated(default(T), count);
}
public static List Repeated(T value, int count)
{
List ret = new List(count);
ret.AddRange(Enumerable.Repeat(value, count));
return ret;
}
}
You could use Enumerable.Repeat(default(T), count).ToList()
but that would be inefficient due to buffer resizing.
Note that if T
is a reference type, it will store count
copies of the reference passed for the value
parameter - so they will all refer to the same object. That may or may not be what you want, depending on your use case.
EDIT: As noted in comments, you could make Repeated
use a loop to populate the list if you wanted to. That would be slightly faster too. Personally I find the code using Repeat
more descriptive, and suspect that in the real world the performance difference would be irrelevant, but your mileage may vary.