Mouhong Lin
Mouhong Lin

Reputation: 4509

Do I need to provide an empty protected constructor for an abstract class?

I know that constructors in abstract classes should be protected in C#.

But some abstract classes do not need non-parameterless constructors. For example:

public abstract MyAbstractClass {
    public abstract Method1();
    public abstract Method2();
    // non-parameterless constructors are not needed
}

My question is, in the above class, do I need to provide an empty protected constructor to override the default implicit constructor? That is:

public abstract MyAbstractClass {
    protected MyAbstractClass() { }

    public abstract Method1();
    public abstract Method2();
}

If I don't provide this empty protected constructor, there'll be an implicit default constructor, which is public (correct?). This breaks the rule that "constructors in abstract classes should not be public".

But when I check the source code of ASP.NET MVC framework, I see that they do not provide empty protected constructor for abstract classes. So, maybe the design rule should be:

If you define constructors in abstract classes, they should not be public.

If you don't need non-parameterless constructors in abstract classes, just don't define them.

Any thoughts?

Upvotes: 2

Views: 1643

Answers (1)

Dan
Dan

Reputation: 9837

No, you don't need to declare a protected default constructor. If you don't have anything to do in the constructor of your abstract class, don't declare one. If you do have something to do, marking it protected will be the same as marking it public because the base constructor can only be called by a child, and the child would have protected access anyway.

Upvotes: 6

Related Questions