HockChai Lim
HockChai Lim

Reputation: 1713

how to constraint the Type parameter to a certain interface only

Would it be possible to constraint a Type parameter to only allow caller to pass in class type that implements a certain interface? Take below as example:

public void RegisterProcessors(params Type[] types)

As it is now, caller can pass in any class type to this method. For example:

RegisterProcessors(typeof(string));  

But what I really want is to only allow caller to pass in type that implements the IProcessor interface. Is that possible? Something like below, of course, below is syntactically wrong

public void RegisterProcessors(params Type<IProcessor>[] types)

Upvotes: 2

Views: 55

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063864

No, basically. If you were using generics, you could use

public void RegisterProcessor<T>() where T : IProcessor

But you can't combine that with params, so the caller would need to invoke it once per type. Which might be fine.

Upvotes: 5

Related Questions