Kris
Kris

Reputation: 956

Type.GetMethod returns always null

I want to get a MethodInfo object from the calling method to determine if there is a special attribute set on that method.

The Programm class with the calling method Run()

class Program
    {
        private static RestHandler _handler = new RestHandler();
        static void Main(string[] args)
        {
            Run();
        }

        [Rest("GET")]
        static void Run()
        {   
            _handler.Handler(typeof(Program));
        }
    }

The Class where I would like to determine the custom attribute

public class RestHandler
    {
        public void Handler(Type t)
        {
            StackFrame frame = new StackFrame(1);
            var method = frame.GetMethod();

            MethodInfo methodInfo = t.GetMethod(method.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

            var attributes = methodInfo.GetCustomAttributes<RestAttribute>();
        }
    }

The attribute class

 public class RestAttribute : Attribute
    {
        public RestAttribute(string method)
        {
            Method = method;
        }

        public string Method { get; set; }
    }

My problem here is that the MethodInfo object (methodInfo) is always null even the method object from the stack frame ist set correctly. The property method.Name returns the correct name of the calling method. Why the methodInfo object is always null?

Upvotes: 3

Views: 801

Answers (1)

Oguz Ozgul
Oguz Ozgul

Reputation: 7187

This is a private method:

static void Run()

Add BindingFlags.NonPublic to access it via reflection

MethodInfo methodInfo = t.GetMethod(method.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

Upvotes: 5

Related Questions