Click here to Skip to main content
15,878,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

I have a dynamic object created. I need to pass this as a generic type to a method. How would I able to achieve the same ?

Example :

Say I'm having an dynamic object obj, I have to fetch the type of this object and pass it to the method which expects a generic.

Type type = obj.GetType();

example - ClassA<t> class = new ClassA<t>();

What I have tried:

I have tried to pass type variable which has type of dynamic object obj to the ClassA<t> class = new ClassA<t>(); but this doesn't work.
Any idea how to handle this scenario ?
Updated 23-Mar-17 11:24am

1 solution

You won't be able to directly create a strongly-typed instance of the class, as the compiler doesn't have enough information to know what the closed generic type is.

You can create a late-bound instance of the type using reflection:
Type t = obj.GetType();
Type myType = typeof(ClassA<>).MakeGenericType(t);
object instance = Activator.CreateInstance(myType);

Or you can use reflection to call a generic method to create and use the instance:
static class Helper
    private static readonly MethodInfo DoStuffMethod = typeof(Helper).GetMethod("DoStuffHelper", BindingFlags.NonPublic | BindingFlags.Static);
    private static void DoStuffHelper<T>(T value)
        var instance = new ClassA<T>();
    public static void DoStuff(object value)
        if (value == null) throw new ArgumentNullException(nameof(value));
        Type t = value.GetType();
        MethodInfo m = DoStuffMethod.MakeGenericMethod(t);
        m.Invoke(null, new[] { value });
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900