Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 293
Hannesh Avatar asked Mar 07 '11 17:03

Hannesh


2 Answers

You could use a covariant interface for ShaderParam<T>:

interface IShaderParam<out T> { ... }
class ShaderParam<T> : IShaderParam<T> { ... }

Usage:

IShaderParam<object>[] parameters = new IShaderParam<object>[5];
parameters[0] = new ShaderParam<string>(); // <- note the string!

But you can't use it with value types like float in your example. Covariance is only valid with reference types (like string in my example). You also can't use it if the type parameter appears in contravariant positions, e.g. as method parameters. Still, it might be good to know about this technique.

like image 147
Jordão Avatar answered Sep 23 '22 16:09

Jordão


Rather late to the game, but here's how: http://www.codeproject.com/Articles/1097830/Down-the-Rabbit-Hole-with-Array-of-Generics

like image 36
Marc Clifton Avatar answered Sep 22 '22 16:09

Marc Clifton