Reputation: 2905
I'm trying to create a class that accepts two generic types (IQueue, IItem) for example:
public class Coordinator<T,K>
where T : IQueue<K>
where K : IItem
{
private T<K> collection = new T<K>();
}
Where:
public interface IQueue<T> where T : IItem
{
}
public class MyQueue<T> : IQueue<T>
where T : IItem
{
}
But the compiler does not like:
private T<K> collection = new T<K>();
Is this at all possible?
Thanks!
Upvotes: 3
Views: 271
Reputation: 9019
I think you might have expected that in "where T : IQueue where K : IItem" there was a sequence, however it actually needs to be explicity defined now. It would be a nice feature if this did work in the future though. Intuitively what you ask makes sense to me.
here's a suggested way to approach it.
public class Coordinator<T> where T : IQueue<T>, new()
{
private T collection = new T();
}
public interface IQueue<T>{}
public interface IItem{}
Upvotes: 0
Reputation: 6547
I think you need to do the following:
public interface IQueue<T> where T : IItem
{
}
public class MyQueue<T> : IQueue<T>
where T : IItem
{
}
Because you are saying: The coordinator gets an IQueue, but you are trying to construct a MyQueue with more specific information.
Using the already discussed Activator
, you can do this without compiler errors:
class Coordinator <T,K>
where T : IQueue<K>
where K : IItem
{
private T collection = (T)Activator.CreateInstance(typeof(T));
}
Upvotes: 3