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
Release: 2025-01-13 07:29:11
Original
757 people have browsed it

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

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

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!

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