Home > Backend Development > C++ > Can I Pass an Instantiated System.Type as a Generic Type Parameter in C#?

Can I Pass an Instantiated System.Type as a Generic Type Parameter in C#?

DDD
Release: 2025-02-01 12:16:11
Original
283 people have browsed it

Can I Pass an Instantiated System.Type as a Generic Type Parameter in C#?

Pass an Instantiated System.Type as a Type Parameter for a Generic Class

The question centers around the feasibility of constructing a generic class with an instantiated Type instance. Specifically, can one create an instance of MyGenericClass where myType is determined dynamically?

The direct approach results in the compiler error "The type or namespace 'myType' could not be found." To overcome this limitation, reflection offers a solution.

Using reflection, one can dynamically create a type compatible with the generic class's type parameter. Here's an example:

public class Generic<T>
{
    public Generic()
    {
        Console.WriteLine("T={0}", typeof(T));
    }
}

class Test
{
    static void Main()
    {
        string typeName = "System.String";
        Type typeArgument = Type.GetType(typeName);

        Type genericClass = typeof(Generic<>);
        // MakeGenericType is badly named
        Type constructedClass = genericClass.MakeGenericType(typeArgument);

        object created = Activator.CreateInstance(constructedClass);
    }
}
Copy after login

Note that while the example uses a single type parameter, multiple parameters are supported. To omit a type parameter for a generic class with multiple parameters, include commas in the placeholders, as seen in the following example:

Type genericClass = typeof(IReadOnlyDictionary<>, <>);
Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);
Copy after login

The above is the detailed content of Can I Pass an Instantiated System.Type as a Generic Type Parameter in C#?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template