How to constrain generic type to must have a construtor that takes certain parameters?

It’s not possible. I’d like to see “static interfaces” to handle this, but don’t expect them any time soon…

Alternatives:

  • Specify a delegate to act as a factory for T
  • Specify another interface to act as a factory for T
  • Specify an interface on T itself for initialization (and add a constraint so that T implements the interface)

The first two are really equivalent. Basically you’d change your proxy class to something like this:

public class GenericProxy<T>
    where T: ClientBase, new()
{
    string _configName;
    T _proxy;
    Func<string, T> _factory;

    public GenericProxy(Func<string, T> factory, string configName)
    {
        _configName = configName;
        _factory = factory;
        RefreshProxy();
    }

    void RefreshProxy() // As an example; suppose we need to do this later too
    {
        _proxy = _factory(_configName);
    }
}

(I assume you’re going to want to create more instances later – otherwise you might as well pass an instance of T into the constructor.)

Leave a Comment