Home > Backend Development > C++ > How Can Reflection Retrieve Property Values from Strings in C#?

How Can Reflection Retrieve Property Values from Strings in C#?

Susan Sarandon
Release: 2025-02-02 19:31:11
Original
822 people have browsed it

How Can Reflection Retrieve Property Values from Strings in C#?

Leveraging C# Reflection to Access Property Values from Strings

Reflection in C# provides a dynamic way to interact with objects at runtime. A common application is retrieving property values when you only have their names as strings.

This technique is particularly useful when dealing with dynamic data or configurations where property names are not known at compile time.

Utilizing Type.GetProperty() and GetValue()

The core of this approach lies in the Type.GetProperty() and GetValue() methods. Here's a concise function demonstrating this:

public static object GetPropertyValue(object obj, string propertyName)
{
    Type type = obj.GetType();
    PropertyInfo property = type.GetProperty(propertyName);
    return property?.GetValue(obj);
}
Copy after login

This function takes an object and a property name (as a string) and returns the property's value. The null-conditional operator (?.) gracefully handles cases where the property doesn't exist, preventing exceptions.

Practical Example

Let's illustrate its usage:

public class MyClass
{
    public string MyProperty { get; set; }
}

// ... later in your code ...

string className = "MyClass";
string propertyName = "MyProperty";

object instance = Activator.CreateInstance(Type.GetType(className));
object propertyValue = GetPropertyValue(instance, propertyName); 
Copy after login

This example dynamically creates an instance of MyClass and retrieves the value of MyProperty using the GetPropertyValue function. This eliminates the need for hardcoded property access and enhances code flexibility.

The above is the detailed content of How Can Reflection Retrieve Property Values from Strings 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