Tuesday, May 15, 2007

Interesting Reflection Problem

First of all, there is no problem with reflection!!!
I didn't get a nice title for this post. So sorry about that :-)

Actually, its a problem that I am trying to solve using reflection.
Here is the problem.

I've been trying to get the value out of a command expression inside an string, something like this:

Class1 ob1 = new Class1();

string strCommand = "ob1.Price"; // price being a property of the ob1 object

int iResult = Exec(strCommand);

In the iResult variable the actual price (a number) should be there. So what i want is that the command inside the strCommand string is executed, and their return value is taken.

I don't think it is possible to do it exactly in the way it has been asked. I tried to have a workaround using reflection. Here it is

class Program
{
static object Exec(object ob, string PropertyName)
{
System.Type objType = ob.GetType();
PropertyInfo property = objType.GetProperty(PropertyName);
return property.GetValue(ob, null);
}
static void Main(string[] args)
{
Console.WriteLine(Exec(System.DateTime.Now, "Day"));
}
}

I am not sure if this is the best way to do it. But thats the only way I can think of doing it :-)

No comments: