So, C # ...

MyClass h = new MyClass(); // так конструктор вызывается MyClass []h = new MyClass[5]; // а так уже нет 

How to correctly declare an array of objects so that for each element a constructor is called in? In C ++, a similar construct works as expected, and the constructor is called.

  • In C ++, the following options work: MyClass array [5]; MyClass * array = new Myclass [5]; And in both cases, constructors are called for each element. The fact that you can manually initialize in a loop is already known. Is it possible that in C #, with such development, there is no ready-made mechanism for initializing objects when creating an array? - kisssko
  • can replace class with structure - Grundy
  • one
    @Grundy is possible, only it will be initialized with default values ​​of types, in other words, zeros and null values. So you still have to run through the array and initiate the internal logic, if there is one. - rdorn
  • 2
    In C ++, in both cases you cite objects in the array itself. In C #, objects of reference types are placed on the heap, and in the array there will only be references to them. Therefore, the array is initialized when it is created, but not by the class objects, which is impossible, but the links, of course, are empty. Consider that you are not creating an array of objects, but an array of pointers, and everything will fall into place. - rdorn
  • @rdorn, it's funny that they wanted to add the ability to declare a constructor without parameters for structures, but changed their mind :) - Grundy

4 answers 4

 MyClass h = new MyClass(); // так конструктор вызывается 

Here you create the object of the class MyClass

 MyClass []h = new MyClass[5]; // а так уже нет 

And here you create an array of links to objects of the class MyClass

To create an array of MyClass objects, you need to create each object yourself:

 MyClass []h = new MyClass[5]; for (int i = 0; i < h.Length; i++) { h[i] = new MyClass(); } 
  • one
    more strictly not "an array of class MyClass", but an array of references to MyClass objects. Therefore, manual creation of objects is required. In cpp, under the same conditions, an array of objects will be created, i.e. the objects themselves will be stored in the cells of the array. - rdorn
  • @rdorn thank you for editing. - MihailPw

No An array is a separate object. That is, roughly speaking, we are not creating “Five objects of the type MyClass”. A: "One object, five MyClass objects in size". As a consequence, you cannot create objects when constructing an array. But objects can be created after creating an array, for example in the initializer:

  MyClass[] mas = { new MyClass(), new MyClass(), new MyClass(), new MyClass(), new MyClass() }; 

Or through "for" (as in the next answer).

  • "One object, five MyClass objects in size" is fundamentally wrong if MyClass is not a structure. The array size for reference types does not depend on the size of the objects and does not contain the objects themselves. - rdorn
  • @rdorn если MyClass не является структурой there is a suspicion that it is not :) - tym32167
  • @ tym32167 I also have a suspicion, but suspicion is only a suspicion =) - rdorn

The AGS17 response is viable, but you can also use the generalized method:

 T[] InitializeArray<T>(int length) where T : new() { T[] array = new T[length]; for (int i = 0; i < length; ++i) { array[i] = new T(); } return array; } 

You can use it like this:

 MyClass[] h = InitializeArray<MyClass>(5); 

The answer is taken from here .

  • What is the profit of using this method? Saving 2 lines of code? It (the method) will make the code a bit slower (or inline?), Requires a bit of memory (which is not critical), and makes the code a little less clear (the reader will have to go through and see what happens inside the method), and the name of the method not quite true, since there is not only the initialization of the array, but also the elements. The method also works only with types with a default constructor. For me, so useless thing. - tym32167
  • one
    With active use, this method will work much slower than when using a cycle - the new T () in generics unfolds in reflection, Activator.CreateInstance, which is much slower than the usual new. - PashaPash
  • @PashaPash, there was already a question and workaround for this :-) - Grundy

This topic was discussed here. How to declare an array of objects in C # . I recommend using this entry:

 MyClass[] arr = new MyClass[5]; arr = arr.Select(x => new MyClass()).ToArray();