0

Possible Duplicate:
C# How can I get the value of a string property via Reflection?
Get property value from string using reflection in C#

When I have a string, I want to compare this with all my property names. When there is a match, how can I return the value of this property?

Class = Setting

Setting has 2 properties.

When I have a string that is the same as one of the propertie names. How can I return the value of that property?

Thanks.

Community
  • 1
  • 1
Sllix
  • 606
  • 9
  • 28

2 Answers2

3

You could use Reflection to read property names and values. For example to get a list of public properties on a type you could use the GetProperties method:

var properties = typeof(Setting);
foreach (var prop in properties)
{
    // here you can access the name of the property using prop.Name
    // if you want to access the value you could use the prop.GetValue method
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

You can use reflection to get properties of your class, You can achieve this by some thing like.

PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public |
                                              BindingFlags.Static);


foreach (PropertyInfo propertyInfo in propertyInfos)
{
  if (propertyInfo.Name == yourString)
  {
       return yourString;
  }
}
Adil
  • 146,340
  • 25
  • 209
  • 204