C# Reflection – MemberInfo Class

MemberInfo class provides a quick look of all the members in a Type. Below is the same code to get all members of a Type.

static void Main(string[] args)
    Type type = typeof(Program);
    foreach(MemberInfo member in type.GetMembers())
        Console.WriteLine(member.Name + ":" + member.MemberType);

MemberInfo MemberType property

MemberInfo provides a property name called MemberType which returns an enum of MemberTypes. MemberTypes specify the type of a Member whether it is property, enum, constructor, method, and NestedType.

Enumeration list of MemberTypes are show below:

ConstructorMember is a constructor
EventMember is an event
FieldMember is a field
MethodMember is a method
PropertyMember is a property
TypeInfoMember is a type
CustomMember is a custom
NestedTypeMember is a nested type
AllSpecifies all member types. Used in search scenarios

BindingFlags Enum

By calling the GetMembers() you will only get the public and public static members of a Type. If we want to get the private and protected members of the type, we have to specify BindingFlags enum value in the GetMembers() method as a parameter.

BindingFlags provides us number of ways by which we can search for members in a C# reflection.

Some important BindingFlags enumeration list are:

IgnoreClaseIgnore the case(uppercase or lowercase) in search term
DeclaredOnlySearch for members specify in the current type not in the base hierarchy
InstanceSearch for instance members
StaticSearch for static members
PublicSearch for public members
NonPublicSearch for non public members like private and protected

Below is the search code for searching public, private protected, static and instance members.

type.GetMembers(BindingFlags.Public | BindingFlags.Instance); //get public members
type.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance); //get private and protected members

type.GetMembers(BindingFlags.Public | BindingFlags.Static); //get public and static members
type.GetMembers(BindingFlags.NonPublic | BindingFlags.Static); //get not public and static members