C# Tips & Tricks #12 – Get property value using Reflection

If you are using Reflection and you wish you get property value using Reflection (string in this example) using C#, you can easily do it using the GetValue() method of the PropertyInfo class as shown below.

public static object GetPropertyValue(object source, string propertyName)
{
        PropertyInfo property= source.GetType().GetProperty(propertyName);
        return property.GetValue(source, null);
  }

How to get the property value using reflection in C#?

Here’s the full code snippet demonstrating the retreival of the property value using reflection at runtime using C#.

using System;
using System.Linq;
using System.Reflection;

namespace ConsoleApp1
{
    public class Employee
    {
        public string Name { get; set; }
    }
    class Program
    {
        private static Random random = new Random();
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            emp.Name = "Senthil";

            string propValue = GetPropertyValue(emp, "Name").ToString();
            Console.WriteLine(propValue);

            Console.ReadLine();
        }
        public static object GetPropertyValue(object source, string propertyName)
        {
            PropertyInfo property= source.GetType().GetProperty(propertyName);
            return property.GetValue(source, null);
        }

    }
}
   
How to get the property value using reflection in C#?

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...