Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type.GetMethod() returns null even though method definitely exists [closed]

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.

like image 898
Shane Ray Avatar asked Feb 23 '17 18:02

Shane Ray


1 Answers

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
    {
    }
}
like image 196
Thomas Weller Avatar answered Nov 04 '22 04:11

Thomas Weller