Reputation: 756
One of the ways of initializing List<T>
with default values (of that type T) is
List<int> foo = new List<int>(new int[5]);
This would create a List with 5 zeroes. How would you do it for List<List<T>>
?
I know we can do it using for loops or using Enumerate.Repeat (but that creates a deep copy) but would like to know if it can be done like above?
Upvotes: 1
Views: 7152
Reputation: 1681
You can use a collection initializer to initialize a list with pre-determined values inline.
object a, b, c, d, e;
var foo = new List<object>()
{
a, b, c, d, e
};
If you want to initialize a list with multiple instances of the same object, the List class doesn't give any solutions. You should probably stick to using a loop.
If you're looking for clever hacks, you can try:
var foo = new List<int>(Enumerable.Range(1, 5).Select(x => 42));
var bar = new List<string>(Enumerable.Range(1, 5).Select(x => "default"));
var far = new List<object>(Enumerable.Range(1, 5).Select(x => new object()));
But don't tell anyone I said that.
Upvotes: 2
Reputation: 70307
Short of creating your own subclass, there is no way to do it.
Upvotes: 0