Property Value Retrieval by Name
An object's property values can be accessed by their respective names, enabling programmatic manipulation and retrieval of data. In certain scenarios, it's desirable to retrieve property values dynamically based on variable property names. This question explores a method to achieve such a functionality.
Method:
The following C# method leverages reflection to obtain the property value of an object based on a specified property name:
public string GetPropertyValue(object obj, string propertyName) { return obj.GetType().GetProperty(propertyName).GetValue(obj, null); }
Usage:
To retrieve the value of the "Make" property from the "car" object:
string make = GetPropertyValue(car, "Make");
Implementation:
The method works as follows:
Additional Points:
The above is the detailed content of How Can I Dynamically Retrieve Property Values in C# by Name?. For more information, please follow other related articles on the PHP Chinese website!