-1

I want to be able to determine which class property has been selected based on a string input by the user, where the string is the name of one of the class properties.

For example

string userInput = "PropertyName";
string newValue = "some value";
MyClass c = new MyClass();
c.PropertyName = newValue;

But I do not know how to locate Properties of a custom class by Name in this way.

Can anyone suggest the most concise way of achieving this please.

PJW
  • 5,197
  • 19
  • 60
  • 74
  • 4
    You can use Reflection, but you should probably rethink the design. Maybe make an indexer instead. – Magus Nov 12 '13 at 16:05
  • 2
    Users don't select class properties. Be careful not to mixup UI design decisions with code design decisions. Key Value Pairs such as a `Dictionary<>` can be used to select an item based on string input from a console. – P.Brian.Mackey Nov 12 '13 at 16:09
  • @P.Brian.Mackey The exception of course are dev tools where you might want to deal with class members by name – Conrad Frix Nov 12 '13 at 16:16

2 Answers2

2

Use reflections:

var prop = c.GetType().GetProperty(userInput,BindingFlags.Public | BindingFlags.Instance)
if(prop != null && prop.CanWrite)
{
    prop.SetValue(c,newValue,null);
}
Michael Mairegger
  • 6,833
  • 28
  • 41
  • Thanks for that, but I am getting the compile error "No overload for SetValue takes 2 arguments". Please advise. – PJW Nov 12 '13 at 16:11
  • Ah, ok. This method is new in .NET 4.5. Prior that you have to use the SetValue method with 3 Parameters. I have updated the answer. – Michael Mairegger Nov 12 '13 at 16:51
0

Thanks for the link to Setting a Property by Reflection

I was able to use the following to achieve my objectives

PropertyInfo propertyInfo = c.GetType().GetProperty(userInput);
propertyInfo.SetValue(c, Convert.ChangeType(newValue, propertyInfo.PropertyType), null);
PJW
  • 5,197
  • 19
  • 60
  • 74