Given the following code why is method variable null?
Type[] typeArgs = { typeof(SomeClass) };
var listRef = typeof(List<>);
var list = Activator.CreateInstance(listRef.MakeGenericType(typeArgs));
var method = list.GetType().GetMethod("Add", BindingFlags.Default, null, typeArgs, null);
I have tried many different overloads and BindingFlags but still never get the MethodInfo for List<SomeClass>.Add(SomeClass item)
.
Surely it is something simple I am missing, but any help would be appreciated.
There are two invisible characters 0x00 0x00
in the string "Add", which is one reason why it does not work. It seems like you did some copy/paste operation.
Next, change the binding flags to BindingFlags.Public | BindingFlags.Instance
:
using System;
using System.Collections.Generic;
using System.Reflection;
namespace GenericReflection
{
class Program
{
static void Main()
{
Type[] typeArgs = { typeof(SomeClass) };
var listRef = typeof(List<>);
var list = Activator.CreateInstance(listRef.MakeGenericType(typeArgs));
var method = list.GetType().GetMethod("Add", BindingFlags.Public | BindingFlags.Instance, null, typeArgs, null);
Console.WriteLine(method);
Console.ReadLine();
}
}
internal class SomeClass
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With