2

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.

1

2 Answers 2

7

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));
Sign up to request clarification or add additional context in comments.

4 Comments

Well that's not much help but I suppose it gives me a direction to travel in. Thanks.
More helpful after the edit - thank you. I actually went out and grabbed a method that contains almost an identical body.
Generics in .NET are NOT compile time, unlike c++.
@LadderLogic: I don't mean that they only exist at compile time; I mean that they form types that are known at compile time.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.