C# Generic Programming – Constructing Objects in Inherited Classes

cgeneric-programming

Basically I am writing a MSMQ based multi-threaded messaging pattern utility library. It's like a set of components all inherited (directly or indirectly) one class that's called my base component class.

Each of these messaging components have the ability to listen to multiple queues via multiple threads and to process messages via multiple threads.

So I have a worker base class that executes itself on a thread, but in implementation you would inherit this class, and fill in the gaps. So I want to be able to basically construct a generic object that inherits this class on the fly, and then put it to work. So far I have this which works, but I am just wondering if there is a better way to do it out there.

My current code…

public class EzQBaseComponent<TWorker> : IEzQComponent where TWorker : EzQWorker
{
    /// LOTS OF CODE YOU DON'T NEED TO KNOW :"D

    private void Listener_MessageRecieved(Guid listenerID, MessageQueue queue, Message msg, MessageQueueTransaction myTransaction)
    {
        try
        {
        lock (m_MessageRecievedLocker)
        {
            if(myTransaction == null)
            {
                // YAWN
            }
            if(msg.Label == c_CustomComponentMessageCommandLabel)
            {
                // YAWN
            }
            else if(Workers.Count < DelegatedWorkers)
            {
                Type t = typeof(TWorker);
                ConstructorInfo[] conInfos = t.GetConstructors();
                ConstructorInfo correctConstructor = null;
                foreach (ConstructorInfo cInfo in conInfos)
                {
                    if (cInfo.GetParameters().Count() < 1)
                    {
                        correctConstructor = cInfo;
                    }
                }

                if (correctConstructor == null)
                {
                    throw new Exception("Generic TWorker class does not contain a consturctor with '0' arguments. Cannot Construct class.");
                }

                TWorker worker = (TWorker)correctConstructor.Invoke(null);

                // YAWN
            }
            else
            {
                // YAWN
            }
        }
    }
    catch (Exception Ex)
    {
        // NOOOO EXCEPTION!!
    }
}

Basically, my base class has a no-parameter constructor. So I look for the one without parameters via reflection, and then use that constructor.

Any thoughts on the construction of the generic object? Is that the best way?

Best Answer

It seems like it would be easier to use the Activator class' CreateInstance method instead:

T worker = (T)Activator.CreateInstance(typeof(T));

It essentially does the same thing. CreatInstance uses the default/parameterless constructor for the type and returns an object (thus the casting). If one doesn't exist, it will throw an exception.

Quick Edit: For your example code, the block would look more like:

else if(Workers.Count < DelegatedWorkers)
{
    try
    {
        TWorker worker = (TWorker)Activator.CreateInstance(typeof(TWorker));
    }
    catch (MissingMethodException ex)
    {
         throw new Exception("Generic TWorker class does not contain a consturctor with '0' arguments. Cannot Construct class.");
    }
}