How to fetch a property value dynamically in C#?

CsharpServer Side ProgrammingProgramming

We can make use of Reflection to fetch a property value dynamically.

Reflection provides objects (of type Type) that describe assemblies, modules and types. We can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If we use attributes in our code, reflection enables us to access them.

The System.Reflection namespace and System.Type class play an important role in .NET Reflection. These two works together and allows us to reflect over many other aspects of a type.


 Live Demo

using System;
using System.Text;
   namespace DemoApplication {
      public class Program {
         static void Main(string[] args) {
            var employeeType = typeof(Employee);
            var employee = Activator.CreateInstance(employeeType);
            SetPropertyValue(employeeType, "EmployeeId", employee, 1);
            SetPropertyValue(employeeType, "EmployeeName", employee, "Mark");
            GetPropertyValue(employeeType, "EmployeeId", employee);
            GetPropertyValue(employeeType, "EmployeeName", employee);
         static void SetPropertyValue(Type type, string propertyName, object instanceObject, object value) {
            type.GetProperty(propertyName).SetValue(instanceObject, value);
         static void GetPropertyValue(Type type, string propertyName, object instanceObject) {
            Console.WriteLine($"Value of Property {propertyName}:                   {type.GetProperty(propertyName).GetValue(instanceObject, null)}");
      public class Employee {
         public int EmployeeId { get; set; }
         public string EmployeeName { get; set; }


The output of the above code is

Value of Property EmployeeId: 1
Value of Property EmployeeName: Mark

In the above example we could see that the Employee properties values are set using Reflection by getting the type and property name. Similarly for fetching the property value we have used GetProperty() method of the Reflection class. By using this we can fetch the value of any property during the runtime.

Published on 08-Aug-2020 14:38:27