Search code examples
c#genericstyping

Array of a generic class with unspecified type


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?


Solution

  • 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.