Home >Backend Development >C++ >How Can I Instantiate a Generic Type in C# with a Variable as the Type Parameter?

How Can I Instantiate a Generic Type in C# with a Variable as the Type Parameter?

Barbara Streisand
Barbara StreisandOriginal
2025-01-13 06:03:43160browse

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:

  1. Get the type of a generic class (for example, List<T>):

    <code class="language-C#">Type genericListType = typeof(List<>);</code>
  2. Replace <T> with the desired type to get a concrete generic type:

    <code class="language-C#">Type specificListType = genericListType.MakeGenericType(typeof(double));</code>
  3. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn