KARPACH

WEB DEVELOPER BLOG

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

Comments

Posted on 11/3/2008 12:38:13 PM by Nela

I need to access a public member of a class using reflection. And then call a method of that member (the member is an instance of another class)

Posted on 11/13/2008 10:01:19 PM by uday

No comment

Posted on 11/30/2008 07:06:14 AM by Dennis B

I’ve been looking for the past 2 days for this. Thank you !!!!!

Posted on 2/22/2010 11:00:08 PM by Anonymous

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);
}

Posted on 2/22/2010 11:02:33 PM by Anonymous

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);
}

Posted on 4/18/2010 10:30:54 PM by Harpreet

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);
}

Posted on 11/2/2011 02:32:32 AM by chani

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);