Princeton
Princeton

Reputation: 425

Type as Generic "T" using reflection

Is it possible for me to do the following?

public static T Merge<T>()
{
     object x = Activator.CreateInstance<T>();
     //Do some stuff with x 
     return (T)x;
}

private static Type[] GetTypesInNamespace(Assembly assembly, string nameSpace)
{
    return assembly.GetTypes().Where(
        t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal) & 
             !t.IsInterface).ToArray();
}

public static void Main()
{
    Type[] typelist = GetTypesInNamespace(
        Assembly.GetExecutingAssembly(), "Myapplication.Web.DomainObjects");

    Parallel.ForEach(typelist, type =>
    {
        var  task1 = Task.Factory.StartNew(() => Merge<type>());
        // is it possible to do this way? Merge<type> ??    
    });
}

Upvotes: 3

Views: 498

Answers (2)

Justin
Justin

Reputation: 86729

No, you can't do this - Generics are used when you know the type in advance at compile time, however you don't in this case.

I believe that what you really want to do is something a little like this:

public static object Merge(Type type)
{
    object x = Activator.CreateInstance(type);
    //Do some stuff with x 
    return x;
}

Your foreach statement now looks slightly different:

Parallel.ForEach(typelist, type =>
{
    var task1 = Task.Factory.StartNew(() => Merge(type));
});

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292425

If you want to call a generic method with a type you don't know at compile time, you need to use reflection :

  Parallel.ForEach(typelist, type => {
    var methodInfo = typeof(YourClass).GetMethod("Merge").MakeGenericMethod(type);
    var  task1 = Task.Factory.StartNew(() => methodInfo.Invoke(null, new object[0]));
  });

Upvotes: 0

Related Questions