Accessing private fields in C#

Based OO principles the private fields should not be accessd by anything outside of the object. However, for some reason we have to access the private fields, a good example is unit testing.

With dotnet reflection we could access any fields, members in an object. The accessibility is controled by BindingFlags, specify proper bindingFlags we can access all private fields in a class. To access the private fields in base class we need to add one more level of the type with BaseType.

Here is the extension method to get the value of a public and private field in an instance.

public static T GetFieldValue<T>(this object obj, string name)
{
	var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
	var field = obj.GetType().GetField(name, bindingFlags);
	if (field == null)
		field = obj.GetType().BaseType.GetField(name, bindingFlags); //father
	else if (field == null)
		field = obj.GetType().BaseType.BaseType.GetField(name, bindingFlags); //granpa
	else if (field == null)
		field = obj.GetType().BaseType.BaseType.BaseType.GetField(name, bindingFlags); //father of granpa

	return (T)field?.GetValue(obj);
}

 269 total views

Author: Albert

Leave a Reply