New as applied to arrays

  • Thread starter Thread starter nick_nw
  • Start date Start date
N

nick_nw

Given:

class MyClass
{
private int var;

public MyClass ()
{
// Any old init code
var = 3;
}
}

class Class1
{
[STAThread]
static void Main(string[] args)
{
MyClass [] array = new MyClass [14];
}
}

What actually happens when new is called? I've looked at the IL and it
seems that the newarr command is called. I've not been any detailed
info on newarr and what it actually does.

The constructor in MyClass is not called so no instances of MyClass are
created. What is new actually doing?

Thanks in advance,

Nick
 
nick_nw wrote:

The constructor in MyClass is not called so no instances of MyClass are
created. What is new actually doing?

new MyClass[14] creates an array with 14 slots, a bit like:

MyClass x1;
MyClass x2;
MyClass x3;
MyClass x4;
etc

Each of these is initially null, because that's the default value for
reference types. (When you create an array, it is filled with the
default value for that type, whatever that type is.)

Jon
 
Nick,

When you create an array you create an object that has slots to hold 14, in
your case, references to instnaces of your class. It doesn't actually
instantiates objects of that class of yours - the array is empty in the
beginning..
 
Back
Top