Why is my default constructor for an array not called here?

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { A[] a = new A[10]; } } public class A { static int x; public A() { System.Console.WriteLine("default A"); } public A(int x1) { x = x1; System.Console.WriteLine("parametered A"); } public void Fun() { Console.WriteLine("asd"); } } } 

Why doesn't my default constructor call here? What am I doing wrong?

+4
source share
4 answers

A[] a = new A[10]; will create an array that can contain 10 instances of A , but the links are initialized to null . First you need to create these instances, for example. a[0] = new A(); .

+4
source

Arrays are initialized to zero by default. These are type containers at hand, not actual type objects.

0
source

You declare an array that can contain 10 instances of A, but you have not yet allocated instances of A. You would have to new A() and put them in an array.

0
source

need to also initialize

  A[] a = new A[2] { new A(), new A() }; A[] a = new A[] { new A(), new A() }; A[] a = { new A(), new A() }; 
0
source

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


All Articles