Archive

Posts Tagged ‘Reflection’

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

June 30th, 2013 No comments

    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: ,

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

December 17th, 2012 3 comments

    Quite often in my practice I need to interact with hidden (internal and private) properties of an object. It easily can be done through the Reflection API. The only complication may arise here it’s when a private property is defined in one of the base classes. In this case we have to iterate through the object’s class hierarchy, looking for the property. So, trying to simplify getting and setting values of object’s private and internal properties, I’ve implemented a couple of the methods-extensions listed below. The GetPropertyValue method returns value of a private or internal property, and the SetPropertyValue, in turn, sets value to a private or internal property.

public static class ReflectionHelper
{
 private static PropertyInfo GetPropertyInfo(Type type, string propertyName)
 {
   PropertyInfo propInfo = null;
   do
   {
     propInfo = type.GetProperty(propertyName, 
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
     type = type.BaseType;
   }
   while (propInfo == null && type != null);
   return propInfo;
 }

 public static object GetPropertyValue(this object obj, string propertyName)
 {
   if (obj == null)
     throw new ArgumentNullException("obj");
   Type objType = obj.GetType();
   PropertyInfo propInfo = GetPropertyInfo(objType, propertyName);
   if (propInfo == null)
     throw new ArgumentOutOfRangeException("propertyName", 
       string.Format("Couldn't find property {0} in type {1}", propertyName, objType.FullName));
   return propInfo.GetValue(obj, null);
 }

 public static void SetPropertyValue(this object obj, string propertyName, object val)
 {
    if (obj == null)
      throw new ArgumentNullException("obj");
    Type objType = obj.GetType();
    PropertyInfo propInfo = GetPropertyInfo(objType, propertyName);
    if (propInfo == null)
      throw new ArgumentOutOfRangeException("propertyName", 
        string.Format("Couldn't find property {0} in type {1}", propertyName, objType.FullName));
    propInfo.SetValue(obj, val, null);
 }
}

Below is how to use the methods. Let’s assume we have the following hierarchy of classes:

class SomeBase
{
    private bool IsLimited { get; set; }

    public SomeBase()
    {
        IsLimited = false;
    }
}

class SomeClass : SomeBase
{
    private  string Str { get; set; }
    internal int    Int { get; set; }

    public SomeClass()
    {
        Str = "initial value";
        Int = 0;
    }
}

So, we need to get and set hidden properties’ values from within a project (library) different to the one where the SomeBase and SomeClass are located. A possible code may look like the following:

SomeClass someObj = new SomeClass();

// the Str and Int properties will be found on the first step of iteration, 
// so, the base class won't be analyzed
string currentStrValue = (string)someObj.GetPropertyValue("Str");
int    currentIntValue = (int)someObj.GetPropertyValue("Int");

// the IsLimited propertiy will be found on the second step of iteration, 
// so, the base class will be analyzed as well
bool currentBoolValue = (bool)someObj.GetPropertyValue("IsLimited");

// the Str and Int properties will be found on the first step of iteration, 
// so, the base class won't be analyzed
someObj.SetPropertyValue("Str", "brand new value");
someObj.SetPropertyValue("Int", -1);

// the IsLimited propertiy will be found on the second step of iteration, 
// so, the base class will be analyzed as well
someObj.SetPropertyValue("IsLimited", true);
Related posts:
Categories: C#, Reflection Tags: ,