Alex Rivera | Logout

Parameterless Constructors

Asked 2010-07-13T02:27:48.370
12

In C#, is there way to enforce that a class MUST have a parameterless constructor?

Edit
Report

1 Answer

16

If you're talking about generic constraints, yes:

class SomeContainer<T> where T : new() {
    ...
}

If you're talking about inheritance. It is not possible to require that every class that implements your interface or inherits your base class has a parameterless constructor.

The best you can do is use reflection in your base constructor to throw an exception (at runtime), like this:

abstract class MyBase {
    protected MyBase() {
        if (GetType().GetConstructor(Type.EmptyTypes) == null)
            throw new InvalidProgramException();
    }
}

If you're talking about a single class, yes; just put one in.

answered 2010-07-13T02:31:10.407

Your Answer