Why is my default constructor for array not getting 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 is my default constructor not getting called here? What Am i doing wrong?
A[] a = new A[10];
will only create an array that can hold 10 instances of A
, but the references are initialized to null
. You will have to create those instances first, e.g. a[0] = new A();
.
Arrays by default are initialized with null values. They are containers of the type at hand, not actual objects of the type.
need to initialize as well
A[] a = new A[2] { new A(), new A() };
A[] a = new A[] { new A(), new A() };
A[] a = { new A(), new A() };
You're declaring an array that can hold 10 instances of A, but you have not allocated any A instances yet. You would have to new A()
and put them in the array.
精彩评论