I wonder if there is better way to initialize an array of reference type object, like this.
Queue[] queues = new Queue[10];
for (int i
I have the same answer - to use a loop. But you can make it as an extension method for general purpose:
public static void Init<T>(this IList<T> array )
{
if (array == null) return;
for (int i = 0; i < array.Count; i++)
array[i] = Activator.CreateInstance<T>();
}
and the just call it:
Queue<int>[] queues = new Queue<int>[10];
queues.Init();
No, there isn't. Just factor it out into a utility method:
// CommonExtensions.cs
public static T[] NewArray<T> (int length) where T : class, new ()
{
var result = new T[length] ;
for (int i = 0 ; i < result.Length ; ++i)
result[i] = new T () ;
return result ;
}
// elsewhere
var queues = Extensions.NewArray<Queue<int>> (10) ;
You could use this:
Enumerable.Range(0,10).Select(_=>new Queue<int>()).ToArray()
But IMO your first example is perfectly fine too.