tags:

views:

98

answers:

1

I have this function

public DataSet Fetch(string EntityName, ObjectParameter[] parameters, int pagesize, int pageindex)
    {
        Assembly asm = Assembly.Load("NCR.WO.PLU.ItemEDM");
        Type _type = asm.GetTypes().Where(t => t.Name.Equals(EntityName)).ToList().FirstOrDefault();

        object obj = Activator.CreateInstance(_type);

        return DataPortalFetch<???>(parameters, pagesize, pageindex);
    }

how do i pass that _type to the generic part??

+7  A: 

You have to call the method using reflection. Generics are designed for types which are known at compile-time; you don't know the type at compile-time, therefore you have to jump through some hoops. It'll be something along the lines of:

MethodInfo method = typeof(WhateverClass).GetMethod("DataPortalFetch");
MethodInfo constructed = method.MakeGenericMethod(new Type[] { _type });
return constructed.Invoke(this, new object[] {parameters, pagesize, pageindex});

The details will depend on whether it's an instance method or a static method, whether it's public or private etc - but the basics are:

  • Get the generic method definition
  • Construct a method with the right type (effectively: pass the type argument)
  • Invoke that constructed method

You may want to cache the generic method definition in a static readonly field, btw - it's reusable.

Jon Skeet
I think that if you don't want to use reflection, you can use Action or Func<> (in .NET 3.5 and Predicate in .NET 2.0) parameters
Tuomas Hietanen
@Tuomas: How would those help if you still need to provide the type arguments at execution time?
Jon Skeet