Cannot create instance of the abstract or interface

Though Abstract classes can contain constructors and the compiler wont raise exception, but when creating object of abstract class the code wont compile, will state error as “Cannot create as instance of the abstract class or interface”

Error Code:

namespace n1
{
abstract class c1
{
public c1()
{
Console.WriteLine("c1");
}
}


class c2: c1
{
public c2()
{
Console.WriteLine("c2");
}
static void Main()
{
c2 c = new c1();
System.Console.ReadLine();
}
}
}

Advertisements

One comment

  1. Imagine that your abstract class has fields x and y, and that you always want them to be initialized in a certain way, no matter what actual concrete subclass is eventually created. So you create a constructor and initialize these fields.

    If you have two different subclasses of your abstract class, when you instantiate them their constructors will be called, and then the parent constructor will be called and the fields will be initialized.
    public abstract class A{
    private string data;
    protected A(string myString){
    data = myString;
    }
    }

    public class B : A {

    B(string myString) : base(mystring){}
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s