0

Let's say I have the following class:

public class SomeClass<TSource>
{

     private Model _model;

     // ...

     public void SomeMethod()
     {
         // ...
         TSource instance = Activator.CreateInstance(typeof(TSource), _model);
         // ...
     }
}

And then I have this class:

public class OtherClass
{
     public OtherClass(Model model)
     {
         // ...
     }
}

If I do the following, everything's fine:

SomeClass<OtherClass> someClass = // ....
someClass.SomeMethod();

But what if OtherClass has a parameterless constructor, or any constructor different than the stated?

Everything will compile just fine, but when creating the instance a runtime exception will be raised.

Is there a way to enforce the use of a certain constructor on every class that will be used as a generic argument to SomeClass<> ? (Like a generic constraint)

Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • 1
    There's no generic constraint for doing this, the best you can do is pass a `Func` to create a new instance. – Lee Jul 28 '16 at 18:36
  • Sorry, I don't think you can force a class to implement a constructor with arguments. But you can do a similar thing by forcing the class to implement an empty constructor, and a method that sets its model – Doc Jul 28 '16 at 18:36
  • @Doc How would you force a class to implement an empty constructor? – MarcinJuraszek Jul 28 '16 at 18:36
  • `public class SomeClass where TSource : new()` – Doc Jul 28 '16 at 18:36

0 Answers0