DigitalJedi805
DigitalJedi805

Reputation: 1460

Passing a 'Type' to a Generic Constructor

Afternoon, evening... whatever it is where you are ;)

I'm working on a 'ThreadManager' that will execute a set of 'ManagedThread<>'s. A managed thread is a generic wrapper for a 'ManagableThread', which contains most of the essential methods.

The list of 'ManagableThread's to start up, is based on what comes out of a configuration file, and is generated in the ThreadManager.Start method. This list, is meant to be populated with all of the 'ManagedThread's that are to be... managed. Here is the code that I am trying to use to complete this task, and as I'm sure any competent C# developer will quickly realize - I'm not gonna swing it like this.

public void Start() {
    foreach (String ThreadName in this.Config.Arguments.Keys) {
        Type ThreadType = null;

        if ((ThreadType = Type.GetType(ThreadName)) == null) {
            continue;
        }
        else {
            ManagedThread<ThreadType> T = new ManagedThread<ThreadType>(
                this,
                this.GetConfiguration(ThreadType)
            );
            this.ManagedThreads.Add(T);

            continue;
        }
    }
}

I've taken a few stabs at this to no avail. If anyone has any suggestions I'd appreciate them. I'm no Generics expert, so this is slightly out of my realm of expertise, so please do refrain from making me cry, but feel free to catch me if I'm a fool.

Thanks in advance to anyone who can offer a hand.

Edit: I suppose I should clarify my issue, rather than make you all figure it out... This code will not compile as I cannot pass 'ThreadType' to the generic parameter for my constructor.

Upvotes: 2

Views: 1847

Answers (2)

David Ly
David Ly

Reputation: 31586

This isn't possible. Generic parameters must be known at compile time. Your type isn't known until runtime.

Upvotes: 0

SLaks
SLaks

Reputation: 887245

That doesn't make sense.
Generics are compile-time types; you can't have a compile-time type that isn't known until runtime.

Instead, you need to use Reflection:

Type gt = typeof(ManagedThread<>).MakeGenericType(ThreadType);
object t = Activator.CreateInstance(gt, this,this.GetConfiguration(ThreadType));

Upvotes: 7

Related Questions