tags:

views:

169

answers:

7

its kinda basic question but still bugging me..

why doesnt

MyObject [] myobject = new MyObject [10];

doesnt allocate 10 objects? why we have to call new on each individual object aswell.

myobject [0] = new MyObject();
.
.
.
myobject [9] = new MyObject();

is that so or I am making some silly mistake? :)

A: 

It's because it only allocates references to MyObject, not the object itself. That's the case with every non-primitive type in languages like C# or Java.

+6  A: 

As far as I am aware, you arent creating 10 objects in the array, you are creating an array with 10 spaces for objects of type "My Object", null is a perfectly acceptable state for an item within the array though.

Mauro
"null is a perfectly acceptable state.." I like it! +1
Cerebrus
A: 

That's exactly how it should be done.

For example:

MyObject[] myObject = new MyObject[10]; // creates 10 null references

for (int i=0;i<myobject.Length;i++)
   myobject[i] = new MyObject();
Philippe Leybaert
A: 

Because all you have created is an array with 10 spaces that will contain your MyObject object instances. When will you put those in and in what state, it's up to you.

Robert Koritnik
A: 

Looks like your talking about C# from the syntax.

More or less, in the CLR/.NET framework, an array is an array which contain's object's of type MyObject. Unlike C/C++, where an array is an array of objects of type MyObject.

i.e. C# array's are simply container's, conceptually they are they are distinct from the object's they hold. C/C++ (native memory), your pretty much cheating and forgo'ng the formality of having clear seporation of duties... your array is essentially the object it contains....

RandomNickName42
+2  A: 

You're calling the array constructor, which creates an array, not the object constructor ten times.

What constructor on the element type would you like to call? There's no way to provide any parameters as it is. The only constructors being called implicitly are value types (structs) like integers and doubles.

What if the element constructor fails? It could throw any exception. Should you get an half initialized array, or no array at all? Should the exception bubble or be hidden?

What if the element constructor is just very very slow. Add a Thread.Sleep() and the code that calls you would basically hang. How would you debug that?

And my last thought, why are you even using arrays when there's List<T>? =)

Simon Svensson
A: 

You could also use the following declaration style (not particularly useful in the following example, I would recommend a for loop instead)

MyObject[] myObject = new MyObject[]{new MyObject(), new MyObject(), new MyObject(), new MyObject(), new MyObject(), new MyObject(), new MyObject(), new MyObject(), new MyObject(), new MyObject()};

however, in this case it could be easier to type.

int[] myInts = new int[]{10,34,13,43,55,2,0,23,6,23};

David