-1

I have an object of a model class.

I have to return the field of the object whose name is provided as a string parameter.

Is there a better way than writing the multiple if conditions.

Thanks in advance.

NutsAndBolts
  • 341
  • 3
  • 13
  • Can you post your existing code? You should be able to use reflection. – Johnathan Barclay Jan 29 '20 at 09:27
  • @JohnathanBarclay: Is there anything unclear in particular in this question that would require any code? I think it would help the OP to know what exactly they should highlight or demonstrate with code, so they can adequately weigh the M and E parts from MWE (minimal working example). – O. R. Mapper Jan 29 '20 at 09:29
  • @O.R.Mapper "return the field" isn't 100% clear to me. Also if code is shown, answers can be in a specific context, which may be more helpful to the OP. – Johnathan Barclay Jan 29 '20 at 09:35

1 Answers1

0

You can use reflection to retrieve the property value by its name.

First, obtain the Type instace that represents your class. For example, use the typeof operator if the type is known at compile-time (including if it is a generic type parameter), or the GetType() method.

Then, you can use GetProperty to retrieve a property with a given name. (Note that there are several overloads of that method that you may need in more complex cases, such as explicit interface implementations.)

The GetProperty method will return a PropertyInfo instance, by means of which you can retrieve the value.

For example:

object propertyValue = myObject.GetType().GetProperty("SomeProperty").GetValue(myObject);
O. R. Mapper
  • 20,083
  • 9
  • 69
  • 114