Home > Backend Development > C++ > How to Dynamically Retrieve Property Values by Name in C#?

How to Dynamically Retrieve Property Values by Name in C#?

Susan Sarandon
Release: 2025-01-06 16:54:40
Original
379 people have browsed it

How to Dynamically Retrieve Property Values by Name in C#?

Retrieving Property Values by Name in C

In C#, a common scenario arises where one needs to dynamically access the value of a property of an object based on its name. This can be useful for generic programming or reflection-based scenarios.

To achieve this, you can leverage the Reflection capabilities of .NET. Here's how:

public string GetPropertyValue(string propertyName)
{
    // Retrieve the type of the object
    Type type = car.GetType();

    // Obtain the property information based on its name
    PropertyInfo property = type.GetProperty(propertyName);

    // Invoke the `GetValue` method to retrieve the property value
    object value = property.GetValue(car, null);

    // Return the property value as a string
    return value.ToString();
}
Copy after login

In this method:

  • car.GetType() obtains the type of the car object.
  • type.GetProperty(propertyName) retrieves the PropertyInfo of the specified property name.
  • property.GetValue(car, null) invokes the GetValue method to retrieve the property value, passing the car object and null for the optional parameters.
  • The property value is returned as a string.

Using this method for the car object with the property name "Make," it will return the value "Ford." This approach allows for flexible and dynamic property value retrieval in C#.

The above is the detailed content of How to Dynamically Retrieve Property Values by Name in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template