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

1
  • 1
    @colinfang please look at the question that is provided as a duplicate Commented Sep 19, 2011 at 16:55

3 Answers 3

2
var type = classA.GetType();
PropertyInfo property = type.GetProperty("A");
var propertyValue = property.GetValue(anInstance, null);
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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

4 Comments

that is not the point of stackoverflow
why isn't it the point of SO ?
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.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.