Home > Backend Development > C#.Net Tutorial > How to set property value via reflection in C#?

How to set property value via reflection in C#?

WBOY
Release: 2023-08-27 15:49:02
forward
652 people have browsed it

How to set property value via reflection in C#?

system. The reflection namespace contains classes that allow you to obtain information about your application and dynamically add types, values, and objects to your application.

Reflection objects are used to obtain type information at runtime. Classes that allow access to a running program's metadata are located in the System.reflection namespace.

Reflection allows viewing property information at runtime.

Reflection allows inspection of various types in an assembly and instantiation of these types.

Reflection allows late binding to methods and properties.

Reflection allows you to create new types at runtime and then use these types to perform some tasks.

Example

GetProperty(String)

Search for a public property with the specified name.

GetType(String, Boolean)

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

SetValue(Object, Object)

Set the property value of the 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; }
}
Copy after login

Output

Bangalore
Copy after login

The above is the detailed content of How to set property value via reflection in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template