Home >Backend Development >C++ >How Can I Access Property Values in C# Using Reflection?
Accessing Property Values by Name
Accessing property values by name is a common task in many programming scenarios. This article demonstrates how to accomplish this by leveraging reflection, a powerful tool in .NET.
Consider the following class and object:
public class Car : Vehicle { public string Make { get; set; } } var car = new Car { Make="Ford" };
To design a method that accepts a property name and returns its value, we can utilize reflection:
public string GetPropertyValue(string propertyName) { return car.GetType().GetProperty(propertyName).GetValue(car, null); }
In this code:
This method allows you to access property values dynamically without relying on hard-coded property names.
The above is the detailed content of How Can I Access Property Values in C# Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!