DCSIMG
Invoke a Static Generic Method using Reflection - Guy Burstein's Blog

Guy Burstein's Blog

Developer Evangelist @ Microsoft

News

Guy Burstein The Bu

Disclaimer
Postings are provided 'As Is' with no warranties and confer no rights.

Guy Burstein LinkedIn Profile

TwitterCounter for @bursteg

Links

Articles

Blogs I Read

Invoke a Static Generic Method using Reflection

Invoke a Static Generic Method using Reflection

Static Generic Method using Reflection

Assume you have a class with a static generic method:

class ClassWithGenericStaticMethod
{
    public static void PrintName<T>(string prefix) where T :
class
    {
        Console.WriteLine(prefix + " " + typeof
(T).FullName);
    }
}

How can you invoke this method using relection?

It turns out to be very easy... This is how you Invoke a Static Generic Method using Reflection:

// Grabbing the type that has the static generic method
Type typeofClassWithGenericStaticMethod = typeof(ClassWithGenericStaticMethod);

// Grabbing the specific static method
MethodInfo methodInfo = typeofClassWithGenericStaticMethod.GetMethod("PrintName", System.Reflection.BindingFlags.Static | BindingFlags
.Public);

// Binding the method info to generic arguments
Type[] genericArguments = new Type[] { typeof(Program
) };
MethodInfo
genericMethodInfo = methodInfo.MakeGenericMethod(genericArguments);

// Simply invoking the method and passing parameters
// The null parameter is the object to call the method from. Since the method is
// static, pass null.
object returnValue = genericMethodInfo.Invoke(null, new object[] { "hello" });

Enjoy!

Comments

Aldo said:

Hi Guy,

do you know if there are some known issues about derived classes.

I have a generic class

public abstract class Generic<T>

{

...

}

with a static method into.

I derived the previous and I tried to use your example, but it crashes everytime cause it says the method isn't present.

Could you help me?

Thanks a lot

Regards

ALdo

# February 24, 2007 9:09 PM

גיא בורשטיין said:

Hi Aldo,

I tested your scenarion with this code:

public abstract class AbstractGeneric<T>

{

   public static void PrintName(string prefix)

   {

       Console.WriteLine(prefix);

   }

}

class Program

{

   static void Main(string[] args)

   {

       // Grabbing the type that has the static generic method

       Type typeofGenericClassWithStaticMethod = typeof(AbstractGeneric<>);

       // Grabbing the specific static method

       MethodInfo methodInfo = typeofGenericClassWithStaticMethod.GetMethod("PrintName", System.Reflection.BindingFlags.Static | BindingFlags.Public);

       // Simply invoking the method and passing parameters

       // The null parameter is the object to call the method from. Since the method is

       // static, pass null.

       object returnValue = methodInfo.Invoke(null, new object[] { "hello" });

   }

}

I got an exception: "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true." which makes sense. Calling a static method requires a valid type, and a generic class without type arguments is not valid.

Additionaly, without refloection, the following code is also invalid:

AbstractGeneric<>.PrintName("guy");

I hope I got your scenario OK, and this helped.

Contact me again at any time.

Guy

# February 24, 2007 9:49 PM

Guy Burstein's Blog said:

This is my #200 post, and it is a good time to look back at what I've posted over the last few months.

# March 9, 2007 8:51 PM

Tommy said:

Hello guy,

Thanks for the freat article.

I'm trying this code for a while and couldn't get it to work. I was wondering if you can look and see where I'm going wrong.

I have some tables in the database and I want to get all the lookup values and I have 100 different tables. I don't want to write the same code 100 times to get the results. Instead I created a generic lookup method that I pass the name of the class and it gets me the values.

Same case here I want to get the values of the tables and 3rd party code does that for me,

For Example I have T1, T2, T3 and this is what that class accepts

public System.Collections.Generic.IEnumerable<T> Entities<T>()

where T : Entity

and Entity has : Name, Phone Number and so on.....

Now to get the data from above I do is

foreach (T1 in Entities<T1>()) // Works No Problem

foreach (T2 in Entities<T2>()) // Works No Problem

foreach (T3 in Entities<T3>()) // Works No Problem

Above all three lines work well but I have to write it 100 times to get data from 100 tables.

I want to have some generc something along these lines  but can't get it to work.....

public static IList<AbstractKeyValueEntity<T>> GetAllLookupValues()

{

IList<AbstractKeyValueEntity<T>> values = new List<AbstractKeyValueEntity<T>>();

foreach(AbstractKeyValueEntity<T> entity in I can't figure out what will be here)

{

values.Add((AbstractKeyValueEntity<T>)entity);

}

return values;

}

# May 13, 2007 9:06 PM

גיא בורשטיין said:

Hi Tommy, thanks for the feedback. I am glad to hear that you liked it.

Please send me a Visual Studio Project with the above scenario, and I'll try to respond ASAP.

Guy

# May 13, 2007 11:18 PM

גיא בורשטיין said:

Sure,

guyb at advantech dot co dot il

# May 14, 2007 7:07 AM

alain tesio said:

Hi here is a problem:

- you load an assembly at runtime with Assembly.LoadFile

- you call a static method from this assembly to deserialize a file into a type known in this assembly

- you get the message "Assembly ... is not loaded ..." as if the assembly itself does not know how to find itself

A solution is:

- Handle the event AppDomain.CurrentDomain.AssemblyResolve

- If the name of the assembly being resolved matches an assembly you're loading dynamically, help the runtime and return it

# July 31, 2007 9:44 PM

Microsoft » Blog Archive » Invoke a Static Generic Method using Reflection - Guy Burstein’s… said:

Pingback from  Microsoft  &raquo; Blog Archive   &raquo; Invoke a Static Generic Method using Reflection - Guy Burstein&#8217;s&#8230;

# May 13, 2008 7:44 PM

reflection static generic type said:

Pingback from  reflection static generic type

# June 2, 2008 10:22 PM

сайдинг said:

2bThank's.9k I compleatly agree with last post.

<a href="all-siding.ru/index.php сайдингом</a> 6z

<a href="all-siding.ru/index.php канадский</a> 4s

# August 18, 2008 7:09 AM

Jeremy Holt said:

Hi - I'm trying to convert the following (from a DataContext) into a generic method.

//[Function(Name = "dbo.fnVisitorsLog", IsComposable = true)]

       //public IQueryable<fnVisitorsLogResult> fnVisitorsLog()

       //{

       //    return this.CreateMethodCallQuery<fnVisitorsLogResult>(this, ((MethodInfo)(MethodBase.GetCurrentMethod())));

       //}

Using this code I get System.Reflection.ParameterCountException: Parameter count mismatch.

      protected virtual IQueryable<T> GetResult()

       {

           Type typeofClassWithGenericStaticMethod = typeof(DataContext);

           MethodInfo methodInfo = typeofClassWithGenericStaticMethod.GetMethod("CreateMethodCallQuery", BindingFlags.NonPublic | BindingFlags.Instance);

           var genericArguments = new[] { typeof(T) };

           MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(genericArguments);

           object returnValue = genericMethodInfo.Invoke(context, new object[]{});

           return (IQueryable<T>) returnValue;

       }

Any idea what I'm doing wrong?

Many thanks in advance

Regards

# August 19, 2008 6:08 PM

... said:

Gut!

# March 2, 2009 3:03 AM

Tom said:

Thanks Guy!  That did the trick!

# May 15, 2009 3:15 AM

goblins said:

Helped me a lot!

# July 8, 2009 3:39 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: