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
objecttype 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.GetPropertysearches only forpublicproperties. If you need to accessprivateproperties, you must specifyBindingFlags.
