3

Possible Duplicate:
Get property value from string using reflection in C#

say, classA has properties A,B,C,D,E.. I wanna build a method StringToProperty so that StringToProperty("A") returns A.

I guess it can be done by reflection, but i have no knowledge of it now. Any simple examples?

THx, i will close it, plz vote to close

Community
  • 1
  • 1
colinfang
  • 20,909
  • 19
  • 90
  • 173

3 Answers3

2
var type = classA.GetType();
PropertyInfo property = type.GetProperty("A");
var propertyValue = property.GetValue(anInstance, null);
vc 74
  • 37,131
  • 7
  • 73
  • 89
2

Are you writing the method in the class that has the properties? If so just do the following:

public object StringToProperty(string prop)
{
    switch(prop)
    {
        case "A":
           return a;
        case "B":
           return b;

    }
}

Or you can just use reflection if not:

Type type = classA.GetType();
return type.GetProperty(propertyString).GetValue(classAInstance, null);
Ian Dallas
  • 12,451
  • 19
  • 58
  • 82
  • +1 for the very simply switch block solution. (Even if the OP was *looking* for an example of Reflection, I think it's a better solution!) – Kevek Sep 19 '11 at 17:02
1

If you do a very simple Google search you can find lots written about this!

Here's the first article I found that talks about exactly what you need.

And you could very easily write:

public object StringToProperty(string propertyName)
{
   Type type = ClassA.GetType();
   PropertyInfo theProperty = type.GetProperty(propertyName);

   object propertyValue = theProperty.GetValue(yourClassAInstance, null);
   return propertyValue;
}
Kevek
  • 2,534
  • 5
  • 18
  • 29
  • 1
    that is not the point of stackoverflow – msarchet Sep 19 '11 at 16:55
  • why isn't it the point of SO ? – Seb Sep 19 '11 at 17:00
  • In the first FAQ question it clearly states "Please look around to see if your question has been asked before." One method to doing this is going straight to the search in StackOverflow. Another (even more broad, that often returns StackOverflow) is Google. I'm simply pointing out that this is a pretty common issue that people have written a lot about and it may be *better* to go do a little research first. This is encouraged by StackOverflow, too. So your sarcasm is a little out of place. – Kevek Sep 19 '11 at 17:00
  • @Seb he's referring to the initial part where I mentioned that you could find an answer from Google (or StackOverflow) very quickly for this issue. – Kevek Sep 19 '11 at 17:01