Home >Backend Development >C++ >How Can I Instantiate a Generic Type in C# with a Variable as the Type Parameter?
instantiate a C# generic type using variables as type parameters
In C#, it is often necessary to create instances of generic types based on dynamically determined type parameters. However, providing type parameter values directly in the new
keyword is not possible and results in the following error:
<code>'List<k>' is a 'Type' but is used like a 'Type'</k></code>
Solution
To overcome this limitation, reflection can be used to explicitly construct generic types:
Get the type of a generic class (for example, List<T>
):
<code class="language-C#">Type genericListType = typeof(List<>);</code>
Replace <T>
with the desired type to get a concrete generic type:
<code class="language-C#">Type specificListType = genericListType.MakeGenericType(typeof(double));</code>
Use reflection to create an instance of a specific generic type:
<code class="language-C#">var list = Activator.CreateInstance(specificListType);</code>
With this approach, you can create instances of a generic type that use variable-driven type parameters.
The above is the detailed content of How Can I Instantiate a Generic Type in C# with a Variable as the Type Parameter?. For more information, please follow other related articles on the PHP Chinese website!