Reputation: 43254
Imagine I have an interface that specifies some collection handler:
interface ICollectionHandler<T> where T : new() { ... }
I then have same other class that wants a collection handler, which it will use for various types, so I want to do something like:
class SomeClass<T> where T : ICollectionHandler<> ...
If I do this though, I get an error saying that the "Type argument is missing".
So is there a way of specifying that T is a generic type, whose own type argument can be specified at runtime, or am I pushing C# beyond its (possibly sensible) boundaries here?
Upvotes: 3
Views: 253
Reputation: 51634
You can create a base interface for ICollectionHandler<T>
and constrain against it.
interface ICollectionHandler { ... }
interface ICollectionHandler<T> : ICollectionHandler where T : new() { ... }
class SomeClass<T> where T : ICollectionHandler { ... }
Or add a parameter to SomeClass
representing the Type that should be passed into the ICollectionHandler<T>
constraint:
class SomeClass<T, U> where T : ICollectionHandler<U> { ... }
Upvotes: 3
Reputation: 21004
You could try something like:
interface ICollectionHandler<T> where T : new() { }
public class MyImplementation<T, U> where T : ICollectionHandler<U> { }
I'm pretty sure that knowing which generic type reside inside your implementation of your interface is required. If you don't care about that sub-type:
interface ICollectionHandler { }
public abstract class CollectionHandler<T> : ICollectionHandler where T : new() { }
public class MyImplementation<T> where T : ICollectionHandler { }
But it really depends how you are gonna use that and in what context. Maybe you can give more details?
Upvotes: 5
Reputation: 18985
You can add a second type parameter to SomeClass
:
class SomeClass<T, U> where T : ICollectionHandler<U> ...
Upvotes: 2