1

I wrote this function:

public static MethodInfo[] GetMethods<T>()
{
    return typeof(T).GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
}

It seems to work fine for classes that do not inherit any other type:

class A
{
    private void Foo() { }
}

var methods = GetMethods<A>(); // Contains void Foo()

But when I run the function on a class that inherits another, it fails to get the base class's private methods:

class B : A
{
    private void Bar() { }
}

var methods = GetMethods<B>(); // Contains void Bar(), but not void Foo() :(

I know that I could define void Foo() as protected, but I am dealing with third party code, where I am not able to do so.

So how do I iterate over the private functions of a class and it's parent classes?

Simon Farshid
  • 2,636
  • 1
  • 22
  • 31
  • 3
    See [duplicate](http://stackoverflow.com/questions/2267277/get-private-properties-method-of-base-class-with-reflection), check `Type.BaseType` (while that isn't `null`!). :) – CodeCaster Oct 06 '15 at 13:47
  • 1
    Private members are not inherited, thus the derived type has no knowledge of them (even via reflection). – D Stanley Oct 06 '15 at 13:50
  • Voting to reopen as the suggested duplicate only checks the inheritance hierarchy one level deep and I'd like to post my current solution. – Simon Farshid Oct 06 '15 at 13:58

1 Answers1

3

I have solved this by running GetMethods recursively until I reach the end of the inheritance tree.

public static IEnumerable<MethodInfo> GetMethods(Type type)
{
    IEnumerable<MethodInfo> methods = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

    if (type.BaseType != null)
    {
        methods = methods.Concat(GetMethods(type.BaseType));
    }

    return methods;
}
Simon Farshid
  • 2,636
  • 1
  • 22
  • 31