Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to set a property value by reflection in C#?
The System.Reflection namespace in C# provides classes that allow you to obtain information about applications and dynamically add types, values, and objects at runtime. One of the most common uses of reflection is setting property values dynamically when you don't know the property name at compile time.
Reflection allows you to examine various types in an assembly, instantiate these types, perform late binding to methods and properties, and even create new types at runtime.
Syntax
Following is the syntax for setting a property value using reflection −
Type type = obj.GetType();
PropertyInfo property = type.GetProperty("PropertyName");
property.SetValue(obj, value);
Key Reflection Methods
The following methods are commonly used when working with property reflection −
GetType() − Gets the Type object for the current instance.
GetProperty(String) − Searches for the public property with the specified name.
SetValue(Object, Object) − Sets the property value of a specified object.
GetValue(Object) − Gets the property value from a specified object.
Using GetProperty() and SetValue()
Example
using System;
using System.Reflection;
class User {
public int Id { get; set; }
public string Name { get; set; }
}
class Program {
static void Main(string[] args) {
User user = new User();
Type type = user.GetType();
PropertyInfo prop = type.GetProperty("Name");
prop.SetValue(user, "Bangalore");
Console.WriteLine("Name: " + user.Name);
PropertyInfo idProp = type.GetProperty("Id");
idProp.SetValue(user, 123);
Console.WriteLine("Id: " + user.Id);
}
}
The output of the above code is −
Name: Bangalore Id: 123
Setting Multiple Properties Dynamically
Example
using System;
using System.Reflection;
class Employee {
public int EmpId { get; set; }
public string EmpName { get; set; }
public double Salary { get; set; }
}
class Program {
static void Main(string[] args) {
Employee emp = new Employee();
Type type = emp.GetType();
// Set multiple properties using reflection
string[] propertyNames = {"EmpId", "EmpName", "Salary"};
object[] values = {101, "John Doe", 75000.50};
for (int i = 0; i < propertyNames.Length; i++) {
PropertyInfo prop = type.GetProperty(propertyNames[i]);
if (prop != null) {
prop.SetValue(emp, values[i]);
}
}
// Display values
Console.WriteLine($"Employee ID: {emp.EmpId}");
Console.WriteLine($"Employee Name: {emp.EmpName}");
Console.WriteLine($"Salary: {emp.Salary}");
}
}
The output of the above code is −
Employee ID: 101 Employee Name: John Doe Salary: 75000.5
Setting Properties with Error Handling
Example
using System;
using System.Reflection;
class Product {
public string ProductName { get; set; }
public decimal Price { get; set; }
}
class Program {
static void SetPropertyValue(object obj, string propertyName, object value) {
try {
Type type = obj.GetType();
PropertyInfo prop = type.GetProperty(propertyName);
if (prop == null) {
Console.WriteLine($"Property '{propertyName}' not found.");
return;
}
if (!prop.CanWrite) {
Console.WriteLine($"Property '{propertyName}' is read-only.");
return;
}
prop.SetValue(obj, value);
Console.WriteLine($"Property '{propertyName}' set successfully.");
}
catch (Exception ex) {
Console.WriteLine($"Error setting property: {ex.Message}");
}
}
static void Main(string[] args) {
Product product = new Product();
SetPropertyValue(product, "ProductName", "Laptop");
SetPropertyValue(product, "Price", 999.99m);
SetPropertyValue(product, "InvalidProperty", "Test");
Console.WriteLine($"Product: {product.ProductName}, Price: ${product.Price}");
}
}
The output of the above code is −
Property 'ProductName' set successfully. Property 'Price' set successfully. Property 'InvalidProperty' not found. Product: Laptop, Price: $999.99
Conclusion
Setting property values using reflection in C# provides powerful runtime flexibility when property names are not known at compile time. Use GetType() to get the object's type, GetProperty() to find the property, and SetValue() to assign the value dynamically.
