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

CsharpServer Side ProgrammingProgramming

The System. Reflection namespace contains classes that allow you to obtain information about the application and to dynamically add types, values, and objects to the application.

Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System. Reflection namespace.

Reflection allows view attribute information at runtime.

Reflection allows examining various types in an assembly and instantiate these types.

Reflection allows late binding to methods and properties.

Reflection allows creating new types at runtime and then performs some tasks using those types.

Example

GetProperty(String)

Searches for the public property with the specified name.

GetType(String, Boolean)

Gets the Type object with the specified name in the assembly instance and optionally throws an exception if the type is not found.

SetValue(Object, Object)

Sets the property value of a specified object.

class Program{
   static void Main(string[] args){
      User user = new User();
      Type type = user.GetType();
      PropertyInfo prop = type.GetProperty("Name");
      prop.SetValue(user, "Bangalore", null);
      System.Console.WriteLine(user.Name);
      Console.ReadLine();
   }
}
class User{
   public int Id { get; set; }
   public string Name { get; set; }
}

Output

Bangalore
raja
Published on 05-Nov-2020 18:23:15
Advertisements