In C#, is there way to enforce that a class MUST have a 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.
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?
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() .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With