Home >Backend Development >C++ >How Can I Dynamically Create Generic Instances in C# Using Type Variables?

How Can I Dynamically Create Generic Instances in C# Using Type Variables?

Susan Sarandon
Susan SarandonOriginal
2025-01-13 07:09:42356browse

How Can I Dynamically Create Generic Instances in C# Using Type Variables?

Dynamic creation of generic instances using type variables

In C#, generic types provide a convenient way to define and use data structures that can work with various data types. However, in some cases, you may need to create an instance of a generic type using a variable of the containing type.

The following code attempts to create a List instance using a variable k containing a double type. However, it fails to compile:

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

To solve this problem, you can use the following methods:

  1. Create a variable of type Type to store the generic list type.
  2. Create a specific type (List in this case) using the MakeGenericType method of the generic list type.
  3. Finally, use Activator.CreateInstance to create an instance of the specific list type.

The following is the corrected code:

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

With this approach, you can dynamically create an instance of a generic type using a variable containing the Type . This flexibility allows you to handle complex data structures and scenarios where generic types need to be determined programmatically. Note the typeof(List<>) in <>, it indicates that this is a generic type, not a specific type.

The above is the detailed content of How Can I Dynamically Create Generic Instances 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