Array of a generic class with unspecified type

Hannesh picture Hannesh · Mar 7, 2011 · Viewed 14.5k times · Source

Is it possible in C# to create an array of unspecified generic types? Something along the lines of this:

ShaderParam<>[] params = new ShaderParam<>[5];
params[0] = new ShaderParam<float>();

Or is this simply not possible due to C#'s strong typing?

Answer

Jon Skeet picture Jon Skeet · Mar 7, 2011

It's not possible. In the case where the generic type is under your control, you can create a non-generic base type, e.g.

ShaderParam[] params = new ShaderParam[5]; // Note no generics
params[0] = new ShaderParam<float>(); // If ShaderParam<T> extends ShaderParam

My guess is that this is an XNA type you have no control over though.