开发者

C# abstract class, works with array initialization

As we know that we CANNOT开发者_JAVA百科 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.


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.


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.


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.


in C# arrays are different than the base type. Creator and Creator[] are two different types. Only Creator is abstract. Creator[] is not abstract that's why you can create instances of it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜