How to set a property having different datatype with a string value using reflection in C#?

Reflection in C# allows managed code to examine and manipulate its own metadata, including types, properties, and methods at runtime. This powerful feature enables you to dynamically work with objects without knowing their types at compile time.

A common scenario is when you need to set a property of one data type (like double) using a string value at runtime. This can be accomplished using reflection combined with type conversion.

Syntax

Following is the syntax for getting property information using reflection −

PropertyInfo propertyInfo = obj.GetType().GetProperty("PropertyName");

Following is the syntax for setting a property value with type conversion −

propertyInfo.SetValue(obj, Convert.ChangeType(stringValue, propertyInfo.PropertyType), null);

How It Works

The process involves three key steps:

  1. Get Property Information: Use GetProperty() to obtain metadata about the target property.

  2. Convert Type: Use Convert.ChangeType() to convert the string value to the property's actual data type.

  3. Set Value: Use SetValue() to assign the converted value to the property.

String to Property Type Conversion String "6.5" Convert. ChangeType() Double 6.5 PropertyInfo.PropertyType determines the target conversion type

Example

using System;
using System.Reflection;

namespace DemoApplication {
    class Program {
        static void Main() {
            Circle circle = new Circle();
            string value = "6.5";
            
            PropertyInfo propertyInfo = circle.GetType().GetProperty("Radius");
            propertyInfo.SetValue(circle, Convert.ChangeType(value, propertyInfo.PropertyType), null);
            
            var radius = circle.GetType().GetProperty("Radius").GetValue(circle, null);
            Console.WriteLine($"Radius: {radius}");
        }
    }
    
    class Circle {
        public double Radius { get; set; }
    }
}

The output of the above code is −

Radius: 6.5

Using Multiple Property Types

Example

using System;
using System.Reflection;

namespace DemoApplication {
    class Program {
        static void Main() {
            Product product = new Product();
            
            // Set different property types from string values
            SetPropertyValue(product, "Id", "123");
            SetPropertyValue(product, "Name", "Laptop");
            SetPropertyValue(product, "Price", "999.99");
            SetPropertyValue(product, "InStock", "true");
            
            Console.WriteLine($"Id: {product.Id}");
            Console.WriteLine($"Name: {product.Name}");
            Console.WriteLine($"Price: {product.Price}");
            Console.WriteLine($"InStock: {product.InStock}");
        }
        
        static void SetPropertyValue(object obj, string propertyName, string value) {
            PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName);
            if (propertyInfo != null) {
                var convertedValue = Convert.ChangeType(value, propertyInfo.PropertyType);
                propertyInfo.SetValue(obj, convertedValue, null);
            }
        }
    }
    
    class Product {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public bool InStock { get; set; }
    }
}

The output of the above code is −

Id: 123
Name: Laptop
Price: 999.99
InStock: True

Error Handling

Example

using System;
using System.Reflection;

namespace DemoApplication {
    class Program {
        static void Main() {
            Circle circle = new Circle();
            
            // Valid conversion
            SetPropertySafely(circle, "Radius", "7.5");
            Console.WriteLine($"Radius: {circle.Radius}");
            
            // Invalid conversion attempt
            SetPropertySafely(circle, "Radius", "invalid");
            Console.WriteLine($"Radius after invalid: {circle.Radius}");
        }
        
        static void SetPropertySafely(object obj, string propertyName, string value) {
            try {
                PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName);
                if (propertyInfo != null) {
                    var convertedValue = Convert.ChangeType(value, propertyInfo.PropertyType);
                    propertyInfo.SetValue(obj, convertedValue, null);
                    Console.WriteLine($"Successfully set {propertyName} to {convertedValue}");
                }
            }
            catch (Exception ex) {
                Console.WriteLine($"Error setting {propertyName}: {ex.Message}");
            }
        }
    }
    
    class Circle {
        public double Radius { get; set; }
    }
}

The output of the above code is −

Successfully set Radius to 7.5
Radius: 7.5
Error setting Radius: String 'invalid' was not recognized as a valid Double.
Radius after invalid: 7.5

Conclusion

Using reflection with Convert.ChangeType() allows you to dynamically set properties from string values at runtime. This technique is particularly useful for configuration systems, data binding, and scenarios where property types are determined dynamically. Always include error handling when performing type conversions to handle invalid string values gracefully.

Updated on: 2026-03-17T07:04:36+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements