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