Is it possible to set a constrain that all classes implementing an interface must have, for example, an empty constructor? Like the where T : new() constraint in generic ?
Is it possible to set a constrain that all classes implementing an interface must
Share
There are only four ways I can think of that you might be given a class at run-time which isn’t known at compile-time. You might be given an instance of an object which implements an interface, and want to produce another one like it. That scenario would best be handled by having the interface include a
NewSimilarInstance()method. You might have a method in some class which gets passed a generic type parameter which is constrained to your interface. In that scenario, the routine which accepts the generic parameter could have anew()constraint. Otherwise, you could be given a .netSystem.Typeobject or some other representation (such a string) for the type. In these latter two scenarios, no compile-time validation is going to be meaningful; doing anything with the types will require Reflection, and so you may as well use Reflection to see if they allow the creation of new instances.