Few days back I was looking into .NET Framework design. While playing with server controls I come across requirement where I need to invoke protected member of Object before doing some processing. I found one of the way to access non-public member of Class using reflection.
Here is sample working code
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace Reflection
{
public class A
{
private int m_nMember;
public A()
{
m_nMember = 1;
}
protected int Member
{
get
{
return m_nMember;
}
set
{
m_nMember = value;
}
}
}
class Program
{
static void Main(string[] args)
{
A ObjectA = new A();
Type type = typeof(A);
PropertyInfo oPropertyInfo = type.GetProperty("Member", BindingFlags.Instance | //Specifies that instance members are to be included in the search.
BindingFlags.NonPublic
);
//Get Value of protected property
Object propvalue = oPropertyInfo.GetValue(ObjectA, null);
//Print value of property
Console.WriteLine("Value of " + oPropertyInfo.Name + " = " + propvalue.ToString());
//Set Value of protected property
oPropertyInfo.SetValue(ObjectA, 2, null );
//Again Get Value of protected property
propvalue = oPropertyInfo.GetValue(ObjectA, null);
//Print value of property
Console.WriteLine("Value of " + oPropertyInfo.Name + " = " + propvalue.ToString());
Console.ReadLine();
}
}
}