New as applied to arrays

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
 
J

Jon Skeet [C# MVP]

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
 
S

Stoitcho Goutsev \(100\)

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..
 

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