Examining class members with Reflection and BindingFlags in .NET C#
October 1, 2014 Leave a comment
In this post we saw a basic example of how to read the publicly available members of a class. Here we’ll look at how to refine our search and read other types of members, such as private and static members.
Consider the following, admittedly artificial Customer class:
public class Customer { private string _name; protected int _age; public bool isPreferred; private static int maxRetries = 3; }
We’ll concentrate on the fields to narrow down our focus. Check out the above link to see how to read methods, constructors, properties etc. of a class.
The most basic way of finding the fields of a class is the following:
Type customerType = typeof(Customer); FieldInfo[] fields = customerType.GetFields(); Console.WriteLine("Fields: "); foreach (FieldInfo fi in fields) { Console.WriteLine(fi.Name); }
This will only find the isPreferred variable as it is public. What if we want to get to the private fields as well? Use the BindingFlags enumeration like this:
BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance; FieldInfo[] nonPublicFields = customerType.GetFields(flags); Console.WriteLine("Non-public fields: "); foreach (FieldInfo fi in nonPublicFields) { Console.WriteLine(fi.Name); }
…which results in the following:
Note how the BindingFlags values can be chained together to widen your search. The NonPublic value will find the private, protected and internal variables. This value in itself is not enough to extract the non-public fields, we need to add that we’re interested in class-level fields.
The opposite of non-public is Public:
flags = BindingFlags.Public | BindingFlags.Instance; FieldInfo[] publicFields = customerType.GetFields(flags); Console.WriteLine("Public fields: "); foreach (FieldInfo fi in publicFields) { Console.WriteLine(string.Concat(fi.FieldType, ", ", fi.Name)); }
…which finds ‘isPreferred’ only as expected. We haven’t yet found the static field but it’s straightforward:
flags = BindingFlags.NonPublic | BindingFlags.Static; FieldInfo[] staticFields = customerType.GetFields(flags); Console.WriteLine("Private static fields: "); foreach (FieldInfo fi in staticFields) { Console.WriteLine(string.Concat(fi.FieldType, ", ", fi.Name)); }
…which finds ‘maxRetries’ only as it is the only non-public static field.
View all posts on Reflection here.