Which constructor is used when instantiating an array of objs ?

D

david

I have a question (not sure if just a newbie one, or a stupid one)
whose answer I couldn't find on the C# books and tutorials I could put
my hands on.

Consider the following useless class (could be a struct as well, if
you just comment out the non static parameterless constructor) and the
Main() routine :

using System;

class MyPointC
{
int x;
int y;
internal static int a=-1;

static MyPointC()
{ Console.WriteLine("static constr."); }

public MyPointC()
{ Console.WriteLine("0 args constr."); x=1; y=2;}

public MyPointC(int t)
{ Console.WriteLine("1 args constr."); x=y=t; }
}

public class David
{

public static void Main()
{
int cc=MyPointC.a;
// causes static constructor to run

MyPointC c1=new MyPointC();
// causes 0 args constructor to run

MyPointC c2=new MyPointC(11);
// causes 1 args constructor to run

MyPointC[] vc=new MyPointC[5];
// no explicit constructor seems to run
}
}

The question is :
"How can I instantiate an array of objects (both from a class or a
struct), specifying - as I do when creating single objects - which
constructor should be run, to let, for instance, the array elements
(or anythinhg else) being initialized the way I want ?"


MyPointC[] vc=new MyPointC()[5];
or
MyPointC[] vc=new MyPointC[5]();

are both invalid syntax, rejected by the compiler.


Am I missing a basic thing or two ?!?


Thanks, David
 
O

Ollie

MyPointC[] vc=new MyPointC[5];

does not allocate any instances in the array, it only cretaes the
System.Array object so therefore none of the MyPointC constructors are
called.

you would have to do:

MyPointC[] vc=new MyPointC[5];
vc[0] = new MyPointC();
vc[1] = new MyPointC(11);
vc[1] = new MyPointC(22222);

HTH

Ollie Riches
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top