views:

37

answers:

3

Hey All,

As we know that we CANNOT create the instance of abstract class.

I just want to know that if we create the array of abstract class, it will sure work.

E.g.

public abstract class Creator
{
    public abstract void DoSomething();
}

Creator creator = new Creator(); // this will give you compilation error!

Creator[] creator = new Creator[2]; // this will SURE work and will NOT give you compilation error.

Can anybody please let me know that why this is happening and why it is working with array initialization?

Thanks in advance.

+5  A: 

The values stored in the array during the initialization will all be null, so this doesn't actually create any instance of the abstract class. Array initialization corresponds to the following (correct) line:

Creator creator = null;

Creating arrays of a type AbstractClass[] is actually quite useful, because you can then store references to some concrete (inherited) class in the array. For example:

var objects = new object[2];
objects[0] = "Hello";
objects[1] = new System.Random();

Then you can for example iterate over the objects array and call ToString() on all the objects.

Tomas Petricek
+2  A: 

The thing to remember here, is you're not creating any instances of Creator, you're creating an array of those types, who's value's are null.

Matthew Abbott
+1  A: 
Creator[] creator = new Creator[2];

simply initializes an Array to hold two instances of the Creator class. It doesn't actually instantiate any instances of the class for you. Both of those elements will still be null until you initialize them.

Justin Niessner