Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterless Constructors

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

like image 222
Jason Avatar asked Jul 13 '10 02:07

Jason


People also ask

Why do we need Parameterless constructor?

It is required so that code that doesn't know anything about parameterised constructors can construct one of your objects based on the convention that a parameterless constructor is available. On deserialization, and object instance is required so the deserialization process will create one using this constructor.

What is the difference between default constructor and Parameterless constructor?

A default constructor has no parameters. And nor does a constructor that you write with no parameters. So what is the ultimate difference in c#? Added to this when you inherit a default constructor and a parameterless constructor are they exposed on the inheritting type exactly the same?

What is default constructor?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .


2 Answers

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.

like image 109
SLaks Avatar answered Sep 30 '22 02:09

SLaks


Generics can enforce this, but we aren't always using generics ;p

If you are using unit tests, you could use reflection to find all the types that meet the pattern you want to have parameterless constructors (for example, everything derived from MyBaseObject, or everything in the Foo.Bar namespace), and verify that way (by finding the parameterless constructor).

If you want to assert this at runtime too (perhaps in #DEBUG), things like static constructors can be useful points to inject extra type checks.

like image 41
Marc Gravell Avatar answered Sep 30 '22 02:09

Marc Gravell