C# Error: Parent does not contain a constructor that takes 0 arguments

Kuntady Nithesh picture Kuntady Nithesh · Aug 29, 2011 · Viewed 101.3k times · Source

My code is

public class Parent
{

    public Parent(int i)
    {
        Console.WriteLine("parent");
    }
}

public class Child : Parent
{
    public Child(int i)
    {
        Console.WriteLine("child");
    }

}

I am getting the error:

Parent does not contain a constructor that takes 0 arguments.

I understand the problem is that Parent has no constructor with 0 arguments. But my question is, why do we need a constructor with zero arguments? Why doesn't the code work without it?

Answer

dlev picture dlev · Aug 29, 2011

Since you don't explicitly invoke a parent constructor as part of your child class constructor, there is an implicit call to a parameterless parent constructor inserted. That constructor does not exist, and so you get that error.

To correct the situation, you need to add an explicit call:

public Child(int i) : base(i)
{
    Console.WriteLine("child");
}

Or, you can just add a parameterless parent constructor:

protected Parent() { }