Yacoub Massad's answer is correct, but with a little change, you do not need to run MakeGenericType for every CreateQueue call.
The following code runs MakeGenericType once for each type, because for each type QueueFactory<T> there is a separate static variable, QueueFactory<int>.queueType will get StructQueue<int> , and QueueFactory<string>.queueType will get RefQueue<int>
public class QueueFactory<T> { static Type queueType = typeof(T).IsValueType ? typeof(StructQueue<>).MakeGenericType(typeof(T)) : typeof(RefQueue<>).MakeGenericType(typeof(T)); public static IQueue<T> CreateQueue() { return (IQueue<T>)Activator.CreateInstance(queueType); } }
In my semi-scientific test, he created 1 million copies in about a tenth of the time.
source share