A short way to initialize an array of an object of a reference type

I wonder if there is a better way to initialize an array of an object of a reference type, for example.

Queue<int>[] queues = new Queue<int>[10]; for (int i = 0; i < queues.Length; i++) queues[i] = new Queue<int>(); 

I tried Enumerable.Repeat, but all elements of the array belong to the same instance,

 Queue<int>[] queues = Enumerable.Repeat(new Queue<int>(), 10).ToArray(); 

I also tried Array.ForEach, but it does not work without the ref keyword:

 Queue<int>[] queues = Array.ForEach(queues, queue => queue = new Queue<int>()); 

any other idea?

+4
source share
3 answers

You can use this:

 Enumerable.Range(0,10).Select(_=>new Queue<int>()).ToArray() 

But IMO your first example is fine too.

+6
source

No no. Just use the 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) ; 
+4
source

I have the same answer - use a loop. But you can do this 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 just name it:

  Queue<int>[] queues = new Queue<int>[10]; queues.Init(); 
0
source

Source: https://habr.com/ru/post/1433056/


All Articles