How to get property or class member variable value using reflection?
object obj;
PropertyInfo pi = obj.GetType().GetProperty("VariableName");
YourType value = (YourType)(pi.GetValue(obj, null));
Posted on January 21, 2008 by Viktar Karpach
object obj;
PropertyInfo pi = obj.GetType().GetProperty("VariableName");
YourType value = (YourType)(pi.GetValue(obj, null));
namespace MyNamespace
{
public class MyClass
{
public static string sName;
public static string SName
{
get { return sName; }
set { sName = value; }
}
}
protected void btnAccessProperty_Click(object sender, EventArgs e)
{
MyNamespace.MyClass myCls = new MyNamespace.MyClass();
PropertyInfo pi = myCls.GetType().GetProperty("SName");
string value = (string)(pi.GetValue(null, null));
Response.Write(value);
}
namespace MyNamespace
{
public class MyClass
{
public static string sName;
public static string SName
{
get { return sName; }
set { sName = value; }
}
}
protected void btnAccessProperty_Click(object sender, EventArgs e)
{
MyNamespace.MyClass .SName = "Sheetal";
MyNamespace.MyClass myCls = new MyNamespace.MyClass();
PropertyInfo pi = myCls.GetType().GetProperty("SName");
string value = (string)(pi.GetValue(null, null));
Response.Write(value);
}
namespace MyNamespace
{
public class MyClass
{
public static string sName;
public static string SName
{
get { return sName; }
set { sName = value; }
}
}
protected void btnAccessProperty_Click(object sender, EventArgs e)
{
MyNamespace.MyClass .SName = "Sheetal";
MyNamespace.MyClass myCls = new MyNamespace.MyClass();
PropertyInfo pi = myCls.GetType().GetProperty("SName");
string value = (string)(pi.GetValue(myCls, null));
Response.Write(value);
}
when i send null in the func: getValue(null,null) instead of object i get an error. why??
my code is:
string s=(string)typeof(myClass).GetProperty("myProperty").GetValue(null, null);