In C#, is there way to enforce that a class MUST have a parameterless constructor?
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.
It depends what you mean.
For example, you can constrain a generic type parameter in a class or a method to have a parameter-less constructor with the new
keyword, but there's not a real method of limiting an actual class definition beyond that.
public void DoSomething<T>() where T : new() { }
As mentioned in the official MSDN documentation, the C# compiler automatically generates a parameterless constructor that initializes all member variables to default values. If you wish to enforce your own implementation, you can simply do this:
class BaseClass { BaseClass() { // Implementation of parameterless constructor } }
If you're referring to generic constraints, then refer to SLaks' post.
References
I've encountered a problem like this a number of times, I think there's a requirement for abstract/interface constructors. The trouble is when you're using Activator.CreateInstance
or some other technique to instantiate a type which you may not implement (pretty common IoC). Life would be a whole lot easier if you could force a developer to implement a constructor with the right params - even if the purpose is just to pass the params to the base constructor.
The new()
constraint has helped the problem a bit since 2.0, but it still doesn't solve the problem when using not using generics, or if you do want specific arguments (and don't want to mess about with the awkward ConstructorInfo, which can't be statically checked.)
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.