- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to fetch a property value dynamically in C#?
We can make use of Reflection to fetch a property value dynamically.
Reflection provides objects (of type Type) that describe assemblies, modules and types. We can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If we use attributes in our code, reflection enables us to access them.
The System.Reflection namespace and System.Type class play an important role in .NET Reflection. These two works together and allows us to reflect over many other aspects of a type.
Example
using System; using System.Text; namespace DemoApplication { public class Program { static void Main(string[] args) { var employeeType = typeof(Employee); var employee = Activator.CreateInstance(employeeType); SetPropertyValue(employeeType, "EmployeeId", employee, 1); SetPropertyValue(employeeType, "EmployeeName", employee, "Mark"); GetPropertyValue(employeeType, "EmployeeId", employee); GetPropertyValue(employeeType, "EmployeeName", employee); Console.ReadLine(); } static void SetPropertyValue(Type type, string propertyName, object instanceObject, object value) { type.GetProperty(propertyName).SetValue(instanceObject, value); } static void GetPropertyValue(Type type, string propertyName, object instanceObject) { Console.WriteLine($"Value of Property {propertyName}: {type.GetProperty(propertyName).GetValue(instanceObject, null)}"); } } public class Employee { public int EmployeeId { get; set; } public string EmployeeName { get; set; } } }
Output
The output of the above code is
Value of Property EmployeeId: 1 Value of Property EmployeeName: Mark
In the above example we could see that the Employee properties values are set using Reflection by getting the type and property name. Similarly for fetching the property value we have used GetProperty() method of the Reflection class. By using this we can fetch the value of any property during the runtime.