How to get methods in a type

pnvn picture pnvn · Mar 1, 2012 · Viewed 8.7k times · Source

Given: System.Type instance.

The aim is to get the newly-introduced methods (i don't know the right word) in the type, which are - not inherited - not overridden

I want to use .NET Reflection and I tried the Type.GetMethods() method. But, it returned even inherited and overridden ones.

I thought of filtering after getting all the methods. And I looked at the properties/methods exposed by MethodInfo class. I could not figure how to get what I wanted.

For instance: I have a class, class A { void Foo() { } }

When I invoke typeof(A).GetMethods() , I get Foo along with the methods in System.Object: Equals, ToString, GetType and GetHashCode. I want to filter it down to only Foo.

Does anyone know how to do this?

Thanks.

Answer

Brian Rasmussen picture Brian Rasmussen · Mar 1, 2012

GetMethods has an overload that lets you specify BindingFlags. E.g. so if you need to get all declared, public, instance methods you need to pass the corresponding flags.

var declaredPublicInstanceMethods = 
    typeof(A).GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);