Home > C#, Reflection > C#: How to set or get value of a private or internal field through the Reflection

C#: How to set or get value of a private or internal field through the Reflection

    The given post is an extension to the one How to set or get value of a private or internal property through the Reflection. So, here are two more methods to add to the ReflectionHelper. These methods are implemented as extensions to the object class and simplify getting and setting values of object’s private and internal fields.

public static class ReflectionHelper
{
	//...
	// here are methods described in the post
	// http://dotnetfollower.com/wordpress/2012/12/c-how-to-set-or-get-value-of-a-private-or-internal-property-through-the-reflection/
	//...

	private static FieldInfo GetFieldInfo(Type type, string fieldName)
	{
		FieldInfo fieldInfo;
		do
		{
			fieldInfo = type.GetField(fieldName,
				   BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			type = type.BaseType;
		}
		while (fieldInfo == null && type != null);
		return fieldInfo;
	}

	public static object GetFieldValue(this object obj, string fieldName)
	{
		if (obj == null)
			throw new ArgumentNullException("obj");
		Type objType = obj.GetType();
		FieldInfo fieldInfo = GetFieldInfo(objType, fieldName);
		if (fieldInfo == null)
			throw new ArgumentOutOfRangeException("fieldName",
			  string.Format("Couldn't find field {0} in type {1}", fieldName, objType.FullName));
		return fieldInfo.GetValue(obj);
	}

	public static void SetFieldValue(this object obj, string fieldName, object val)
	{
		if (obj == null)
			throw new ArgumentNullException("obj");
		Type objType = obj.GetType();
		FieldInfo fieldInfo = GetFieldInfo(objType, fieldName);
		if (fieldInfo == null)
			throw new ArgumentOutOfRangeException("fieldName",
			  string.Format("Couldn't find field {0} in type {1}", fieldName, objType.FullName));
		fieldInfo.SetValue(obj, val);
	}
}

The use of methods is shown below:

// get value
string privateValue = (string)someObj.GetFieldValue("_connectionString");
// set value
someObj.SetFieldValue("_connectionString", "some connection string");
Related posts:
 
Categories: C#, Reflection Tags: ,
  1. No comments yet.
  1. No trackbacks yet.