Type.GetMethods() Filtering with BindingFlags in Reflection

Type.GetMethods() method (also Type.GetMembers() can return a certain methods / members based on a criteria by applying BindingFlags filter to it.

You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

To me, using BindingFlags has been frustrated. I almost think of it as you must apply all criterias that the method / member has. I am not even sure if that statement is true / not.

Source: BindingFlags

Get Types That Inherit Certain Interface in Reflection

First approach:

Assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof (ICustomer)));

This approach is sort of workaround by getting all the interfaces that the Type (t) inherits and loop thorough them.

Source: MSDN

 

Second approach (preferred):

Assembly.GetTypes().Where(t => (typeof(ICustomer)).IsAssignableFrom(t));

Type.IsAssignableFrom is method to determine whether the current Type (t) can be assigned from an instance of the specified Type (ICustomer). The specified Type doesn’t have to be an interface.

Source: MSDN

Get Types That Inherit Certain Base Class in Reflection

Sample code:

Assembly.GetTypes().Where(t => t.IsSubclassOf(Customer));

Type.IsSubclassOf method determines whether the current Type (in this case t) is derived from a certain class (in this case Customer).

Source: MSDN