How to call a generic method through reflection?

The Cast extension method lives on the class Enumerable, and you need to call MakeGenericMethod: typeof(System.Linq. Enumerable) . GetMethod("Cast", new {typeof(System.Collections.

IEnumerable)}) . MakeGenericMethod(typeof(S)) . Invoke(null, new object { oObjectType }) update: Because the method is static, the first parameter to Invoke should be null.

Invoke function does not take one parameter so if I put second parameter as "null"I am getting exception. Any clue why? – milan Dec 21 '09 at 17:52 Exception getting is: Invalid number of parameters.

– milan Dec 21 '09 at 17:58 Enumerable.Cast() does not take any "arguments". The argument given in this case is the object you want to call the extension method Cast on. – sixlettervariables Dec 21 '09 at 18:07 but there is no Invoke with just one parameter!?

– milan Dec 21 '09 at 18:17 1 @milan: Apologies, it appears @Rob's code is slightly incorrect. You would call . Invoke(null, oObject) since Cast is static, per MSDN.

Msdn.microsoft. Com/en-us/library/a89hcwhh. Aspx – sixlettervariables Dec 21 '09 at 18:26.

I think you're looking for Type.MakeGenericType.

Here is the complete test code but still it does not work. The last line produce always exception. Is it possible to make it work?

Using System; using System.Collections. Generic; using System. Linq; using System.

Text; using System. Reflection; namespace reflection_tester { class CBase { public string Ja = "I am the base"; } class MyClass01 : CBase { public string _ID; public string ID { get { return _ID; } set { _ID = value; } } } class Program { public static object wrapper() { //return a list of classes MyClass01 IList lstClass01 = new List(); MyClass01 oClass01a = new MyClass01(); oClass01a. ID = "1"; MyClass01 oClass01b = new MyClass01(); oClass01b.ID = "2"; lstClass01.

Add(oClass01a); lstClass01. Add(oClass01b); return lstClass01; } static void Main(string args) { MyClass01 oMy1 = new MyClass01(); oMy1. _ID = "1"; MyClass01 oMy2 = new MyClass01(); oMy2.

_ID = "3"; IList oListType01 = new List(); oListType01. Add(oMy1); oListType01. Add(oMy2); object oObjectType = new object(); oObjectType = oListType01; /* this works */ IEnumerable enumList = oListType01.Cast(); MethodInfo mInfo = typeof(System.Linq.

Enumerable). GetMethod("Cast", new { typeof(System.Collections. IEnumerable) }).

MakeGenericMethod(typeof(CBase)); /* this does not work, why? Throws exception */ IEnumerable enumThroughObject = (IEnumerable)mInfo. Invoke(oObjectType, null); return; } } }.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions