Home >Backend Development >C++ >How Can I Instantiate Generic Types in C# Using Type Variables?

How Can I Instantiate Generic Types in C# Using Type Variables?

Barbara Streisand
Barbara StreisandOriginal
2025-01-13 07:29:11704browse

How Can I Instantiate Generic Types in C# Using Type Variables?

Create a generic type instance using a variable of the containing type

In C#, it may seem counterintuitive that you cannot instantiate a generic type directly using a variable of the containing type. The following code illustrates the problem:

<code class="language-c#">Type k = typeof(double);
List<k> lst = new List<k>(); // 编译错误</code>

This code does not compile because it attempts to use the variable k to specify a generic type. However, there is a workaround that can be used to achieve the desired functionality.

To create a generic type instance using a variable of the containing type, you can leverage reflection and Activator.CreateInstance():

<code class="language-c#">var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));
var list = Activator.CreateInstance(specificListType);</code>

This code works like this:

  1. genericListType Gets the generic List<> type definition.
  2. MakeGenericType() gets the generic type definition and specifies the actual type parameters (double in this case).
  3. Activator.CreateInstance() Instantiates a specific generic type using the specified type parameters.

The above is the detailed content of How Can I Instantiate Generic Types in C# Using Type Variables?. 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