Search code examples
c#genericsruntimegeneric-programming

generic class, how to set the type in runtime?


I have created a generic class, but I know the type in runtime, not in design, so I would like to know how to set the type in runtime.

For example, I have:

public class MyGenericClass<T>
{
....
}

Then I try to use it. I have a method in other class, that consume this generic class. In the constructor of this class, I receive as parameter the type that I want, so I have a type property in which I save the type that I need. So I am trying this:

MyGenericClass<_typeNeeded> myClass = new MyGenericClass<typeNeeded>();

But this does not work.

How can I set the type in runtime in a class that I created?

I am using C# 4.0.

Thanks. Daimroc.

EDIT: What I want to do is the following. I have a class that need to do some queries to the database. This queries always return the same information, a class, but the information that contains this class come from different tables. This is because I need to determinate what query to use. To decide what query to use I use the type that I receive.

Is for this reason that I don't know in design the type, but is in runtime.

I could use an interface that it would be implemented by to classes, and use the interface instantiated with the correct class, but this make me to have a switch or an if in the moment of the instantiation, and this is what I try to avoid, I want something more generic. Also, If I use this solution, to have an if in the moment of the instantion, I can create the generic class, so I would have only one class and it would be more maintainable.


Solution

  • You can create your class in another way, passing to the constructor the type that you want to use and exploit the dynamic keyword.

    For example:

    class MyGeneralClass
    {
        dynamic myVariable;
        Type type;
    
        public MyGeneralClass(Type type)
        {  
            this.type = type;
            myVariable = Activator.CreateInstance(type);
            //And then if your type is of a class you can use its methods      
            //e.g. myVariable.MyMethod();
        }
    
        //If your function return something of type you can also use dynamic
        public dynamic Function()
        {
            return Activator.CreateInstance(type);
        }
    }