How to set a property value by reflection in C# ?


This content was proof-read by Grammarly. You can Try Grammary for FREE

There are times when you want to set the property of an object using reflection in C#. Below is a sample code snippet demonstrating how to do it taking the Employee class as an example and Name as the property.

How to set a property value by reflection in C# ?

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml.Linq;

namespace ACCode
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee employee = new Employee();
            string name = "Test Name 1";
            // use reflection to set the value of the property name.
            PropertyInfo propertyInfo = employee.GetType().GetProperty("Name");
            propertyInfo.SetValue(employee, name);
            Console.WriteLine(employee.Name);
            Console.ReadLine();
        }
    }

    public class Employee
    {
        public string Name { get; set; }
    }
}
Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

%d bloggers like this: