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
Release: 2025-01-13 06:03:43
Original
163 people have browsed it

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>
Copy after login

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>
    Copy after login
  2. Replace <T> with the desired type to get a concrete generic type:

    <code class="language-C#">Type specificListType = genericListType.MakeGenericType(typeof(double));</code>
    Copy after login
  3. Use reflection to create an instance of a specific generic type:

    <code class="language-C#">var list = Activator.CreateInstance(specificListType);</code>
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template