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

CsharpServer Side ProgrammingProgramming

Reflection is when managed code can read its own metadata to find assemblies. Essentially, it allows code to inspect other code within the same system. With reflection in C#, we can dynamically create an instance of a type and bind that type to an existing object. Moreover, we can get the type from an existing object and access its properties. When we use attributes in our code, reflection gives us access as it provides objects of Type that describe modules, assemblies, and types.

Let us say we have a property of type double and in the runtime we actually have the value as string and assign it to the property after changing the type. We can use Convert.ChangeType() - It allows us to use runtime information on any IConvertible type to change representation formats.


 Live Demo

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; }


Radius: 6.5

In the above example we could see that string value "6.5" is converted to actual type double using Convert.ChangeType and assigned to Radius property using reflection in runtime.

Published on 24-Sep-2020 16:24:08