Dynamically Setting Object Property Values Using Reflection and Type Conversion

Nov 21, 2025 · Programming · 8 views · 7.8

Keywords: C# | Reflection | Type Conversion | PropertyInfo | SetValue

Abstract: This article provides an in-depth exploration of dynamically setting object property values using reflection in C#. By analyzing the working principles of the PropertyInfo.SetValue method, it focuses on solving the conversion problem from string values to target types. The article details the application scenarios and limitations of the Convert.ChangeType method, offering complete code examples and exception handling strategies to help developers understand type safety mechanisms in reflection operations.

Fundamentals of Reflection and Property Setting

In C# programming, reflection is a powerful metaprogramming technique that allows inspection and utilization of type information at runtime. Through the APIs provided by the System.Reflection namespace, developers can dynamically obtain type information, create object instances, invoke methods, and access and modify property values.

The PropertyInfo class is one of the core components in the reflection system, encapsulating metadata information about properties. Among its methods, SetValue is used to set property values for specified objects, with multiple overloaded versions available to accommodate different usage scenarios.

Origin of Type Conversion Issues

A common problem when setting property values using reflection is type mismatch. Consider the following scenario: we have a Ship class containing a Latitude property of type double. When we attempt to set this property using the string value "5.5", an ArgumentException is thrown, indicating "Object of type 'System.String' cannot be converted to type 'System.Double'."

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, value, null); // Throws exception

The root cause of this issue is that the SetValue method expects to receive value objects that exactly match the property's declared type. When a string is passed while the property type is double, the system cannot automatically perform type conversion.

Solution: The Convert.ChangeType Method

To resolve type conversion issues, we can use the Convert.ChangeType method. This method can convert values from one type to another based on runtime type information, provided that the target type implements the IConvertible interface.

The modified code is as follows:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
object convertedValue = Convert.ChangeType(value, propertyInfo.PropertyType);
propertyInfo.SetValue(ship, convertedValue, null);

Or in a more concise form:

propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);

How Convert.ChangeType Works

The Convert.ChangeType method performs type conversion through the following steps:

  1. Checks if the source value implements the IConvertible interface
  2. Invokes the appropriate conversion method based on the target type
  3. Handles culture-specific format conversions (such as number and date formats)
  4. Returns the converted object instance

It's important to note that not all type conversions are possible. For example, converting the string "abc" to a double type will throw a FormatException. Therefore, appropriate exception handling mechanisms should be implemented in practical applications.

Overloaded Versions of SetValue Method

The PropertyInfo.SetValue method provides three main overloaded versions:

// Basic version for non-indexed properties
public void SetValue(object obj, object value)

// Version supporting indexed properties
public virtual void SetValue(object obj, object value, object[] index)

// Full-control version supporting binding flags, binder, and culture information
public abstract void SetValue(object obj, object value, 
    BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)

For simple property setting, the first two overloaded versions are typically used. The third version provides finer control, including access modifier checks, parameter type coercion, and culture-specific format handling.

Exception Handling Strategies

When setting property values using reflection, various possible exception scenarios need to be considered:

try
{
    PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName);
    if (propertyInfo != null && propertyInfo.CanWrite)
    {
        object convertedValue = Convert.ChangeType(value, propertyInfo.PropertyType);
        propertyInfo.SetValue(obj, convertedValue, null);
    }
}
catch (FormatException ex)
{
    // Handle format conversion errors
    Console.WriteLine($"Value '{value}' cannot be converted to target type: {ex.Message}");
}
catch (InvalidCastException ex)
{
    // Handle type conversion errors
    Console.WriteLine($"Type conversion failed: {ex.Message}");
}
catch (ArgumentException ex)
{
    // Handle parameter errors
    Console.WriteLine($"Parameter error: {ex.Message}");
}

Performance Considerations and Best Practices

Although reflection provides great flexibility, it comes with relatively high performance overhead. In performance-sensitive scenarios, it is recommended to:

Extended Application Scenarios

This technique of combining reflection with type conversion is particularly useful in the following scenarios:

By appropriately applying reflection and type conversion techniques, developers can build more flexible and extensible application architectures.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.