1

Please explain why this doesn't work? What is it about the constraint IPoolable<T> that the compiler doesn't like? Is it because the generic IPoolable<T> is really just a "template" and there is no inheritance between PoolItem and IPollable<T>?

In the code

public class GenericPool<TPoolable> where TPoolable : IPoolable<T>

while can't T be interpreted as long?

Full code listing:

    public interface IPoolable<T> where T : new()
    {
        T PooledObject { get; }
    }

    public class PoolItem : IPoolable<long>
    {
        private readonly long _id;

        public long PooledObject
        {
            get { return _id; }
        }
    }

    public class GenericPool<TPoolable> where TPoolable : IPoolable<T>
    {
        public T Borrow()
        {
            var item = default(TPoolable);
            return item.PooledObject;
        }

        public void Return(T item)
        {

        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var pool = new GenericPool<PoolItem>();
        }
    }

Just to be clear, I know that I can change GenericPool to

public class GenericPool<TPoolable, T> where TPoolable : IPoolable<T> where T : new()

I am not asking how to fix this code. Instead I am asking the question; why do I have to add T as a type parameter to GenericPool in the first place?

1 Answer 1

3

You can't use IPoolable<T> as a constraint because the generic type parameter T isn't known in that context. As you surmise, IPoolable<T> is essentially a blueprint for an infinite number of types, so without binding T to something (for example, a type parameter of the GenericPool class) it doesn't make sense as a constraint.

The actual error message you should be getting is The type or namespace name 'T' could not be found, which makes sense: T isn't defined anywhere.

Sign up to request clarification or add additional context in comments.

3 Comments

I understand that T "isn't defined" in the GenericPool class but IPoolable<T> is defined. Why do I have to define T twice?
The T in IPoolable<T> is only relevant in the declaration of the interface itself. Outside of that, IPoolable<> has to be declared with a combination of actual types and valid type parameters between the < and the > (with the notable exception of typeof(IPoolable<>) ). Since T is neither a valid type, nor a currently useable type parameter, you don't have valid code.
no, IPoolable<T> isn't defined either, because compiler doesn't know what T is. The only thing that is defined is generic IPoolable interface, which should be parametrized with a type before instantiation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.