Get Property Value Dynamically from Dynamic Objects in C#

Updated on     Kisan Patel

This post will explain you how to get property value dynamically from dynamic objects in C#.

Problem:

How do we get the value for the current property on the current object?

Solution:
To get the current value of the objects property you call GetValue like this, the second parameter is null because it’s not an array:

//Function to get the Property Value
public static object GetPropertyValue(object target, string propName)
{
      return target.GetType().GetProperty(propName).GetValue(target, null);
}

Let’s take one example to understand how above GetPropertyValue method works. Here, I am using the below Student class properties.

public class Student
{
      public int ID { get; set; }
      public string Name { get; set; }
}

In below code, you can see that we have used GetPropertyValue() method that accepts two parameters, one is the object with data and second is the property name which you want to get value. Here, GetType returns the runtime type of the current instance and GetProperty method searches for the public property with the specified name and return type.

using System;
using System.Collections.Generic;

namespace DynamicDataDemo
{
    class Program
    {
        public static void Main(string[] args)
        {
            List students = new List { 
                new Student {ID = 1, Name = "Ravi"},
                new Student {ID = 2, Name = "Ketul"},
                new Student {ID = 3, Name = "Devang"},
            };

            foreach (var student in students)
            {
                Console.WriteLine(student.ID + ". " + GetPropertyValue(student, "Name"));
            }

            Console.ReadLine();
        }

        //Function to get the Property Value
        public static object GetPropertyValue(object SourceData, string propName)
        {
            return SourceData.GetType().GetProperty(propName).GetValue(SourceData, null);
        }
    }
}

the output of the above program…

get-dynamic-property-value


C#

Leave a Reply