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

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...