[C#] How to Get Property Values Dynamically by Name Using Reflection

In C#, you usually access properties using obj.Property where the property name is determined at compile time. However, in library development or generic data processing, there are cases where you need to “retrieve the value of a property specified by a string at runtime.”

The Reflection feature enables this kind of dynamic type manipulation. This article explains how to retrieve object property values by name using the System.Reflection namespace.

目次

Implementing Dynamic Property Retrieval

The following sample code implements a generic method to extract values from an instance of an Employee class by specifying property names as strings (such as “Name” or “Department”).

Sample Code

using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        // 1. Create a data object
        var emp = new Employee
        {
            Id = 101,
            Name = "Kenichi Sato",
            Department = "Development"
        };

        // 2. Retrieve values by specifying property names as strings
        // Normal access: var name = emp.Name;
        object nameValue = GetPropertyValue(emp, "Name");
        object deptValue = GetPropertyValue(emp, "Department");
        object idValue   = GetPropertyValue(emp, "Id");

        Console.WriteLine($"Name: {nameValue}");
        Console.WriteLine($"Dept: {deptValue}");
        Console.WriteLine($"ID  : {idValue}");

        // Check behavior when specifying a non-existent property
        object invalidValue = GetPropertyValue(emp, "Salary");
        if (invalidValue == null)
        {
            Console.WriteLine("The specified property was not found.");
        }
    }

    /// <summary>
    /// Retrieves the value of a named property from an arbitrary object
    /// </summary>
    /// <param name="targetObj">The target instance</param>
    /// <param name="propertyName">The property name</param>
    /// <returns>The property value (or null if not found)</returns>
    public static object GetPropertyValue(object targetObj, string propertyName)
    {
        if (targetObj == null) return null;

        // 1. Get type information (Type) of the object
        Type type = targetObj.GetType();

        // 2. Get property information (PropertyInfo) for the specified name
        // This searches for public instance properties
        PropertyInfo propInfo = type.GetProperty(propertyName);

        // Returns null if the property does not exist
        if (propInfo == null)
        {
            return null;
        }

        // 3. Extract the value from the specific instance (targetObj)
        // For properties requiring no arguments, the second parameter can be null
        return propInfo.GetValue(targetObj);
    }
}

// Sample Data Class
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
}

Explanation and Technical Points

1. Type.GetProperty Method

By calling GetProperty("PropertyName") on the Type object obtained via obj.GetType(), you can acquire a PropertyInfo object. This object contains metadata about the property (type, read/write status, etc.). If the matching property does not exist, it returns null.

2. PropertyInfo.GetValue Method

The GetValue method is used to actually extract the value using the obtained PropertyInfo.

  • 1st Argument: Specify the actual instance you want to extract the value from.
  • Return Value: It returns the value as an object type regardless of the property’s actual type, so you must cast it if you need to use it as a specific type.

3. Note: Performance and Visibility

  • Speed: Access using Reflection can be tens to hundreds of times slower than standard direct access. If you need to call it frequently (e.g., tens of thousands of times in a loop), consider using caching or Expression Trees.
  • Access Rights: By default, type.GetProperty searches only for public properties. If you need to access private properties, you must specify BindingFlags.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次