C# Reflection - MemberInfo Class

C#  C#  reflection 

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:

Name Description
Constructor Member is a constructor
Event Member is an event
Field Member is a field
Method Member is a method
Property Member is a property
TypeInfo Member is a type
Custom Member is a custom
NestedType Member is a nested type
All Specifies 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:

Name Description
IgnoreClase Ignore the case(uppercase or lowercase) in search term
DeclaredOnly Search for members specify in the current type not in the base hierarchy
Instance Search for instance members
Static Search for static members
Public Search for public members
NonPublic Search 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

Join our newsletter and get an occasional email with a technology and dotnetpattern.com news update.