Home >Backend Development >C++ >How Can I Access Property Values in C# Using Reflection?

How Can I Access Property Values in C# Using Reflection?

Susan Sarandon
Susan SarandonOriginal
2025-01-06 16:41:40236browse

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:

  • car.GetType() retrieves the type of the car object.
  • GetProperty(propertyName) retrieves the property based on the specified name.
  • GetValue(car, null) returns the value of the property.

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!

Statement:
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