0

Hi I have to different classes with Same properties and I want to access the peoperties of my classes Dynamically.

public Class1
{
public const prop1="Some";
}
public Class2
{
 public const prop1="Some";
}

And in my code I am getting my class name like this

string classname="Session["myclass"].ToString();";//Say I have Class1 now.

And I want to get the prop1 value .

Something like
 string mypropvalue=classname+".prop1";//my expected result is Some 

/// Type typ=Type.GetType(classname);

Please help me in getting this

Nagaraj
  • 221
  • 2
  • 5
  • 21

2 Answers2

1

Reflection

var nameOfProperty = "prop1";
var propertyInfo = Class1Object.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);

for static:

var nameOfProperty = "prop1";
var propertyInfo = typeof(Class1).GetProperty("prop1", BindingFlags.Static);
var value = propertyInfo.GetValue(myObject, null);

Class reference from string

EDIT (I made example):

class Program
    {
        static void Main(string[] args)
        {

            var list = Assembly.Load("ConsoleApplication4").GetTypes().ToList();
            Type ty = Type.GetType(list.FirstOrDefault(t => t.Name == "Foo").ToString());
            //This works too: Type ty = Type.GetType("ConsoleApplication4.Foo");
            var prop1 
                 = ty.GetProperty("Temp", BindingFlags.Static | BindingFlags.Public);


            Console.WriteLine(prop1.GetValue(ty.Name, null));
            Console.ReadLine();
        }

    }

    public static class Foo
    {
        private static string a = "hello world";
        public static string Temp
        {
            get
            {
                return a;
            }
        }
    }

Msdn

Community
  • 1
  • 1
slavoo
  • 5,798
  • 64
  • 37
  • 39
0

you can use following function to get a property value fron an object dynamically:
just pass object to scan & property name

public static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}
Nitin Sawant
  • 7,278
  • 9
  • 52
  • 98