ConnectSaravana
Posted on June 27, 2023
What is Reflection:
Imagine you have a box, and inside that box, there's a really cool toy car. But you can't open the box to see the car directly. However, you have a special tool called "reflection."
When you use reflection on the box, it's like using the magic mirror on the toy car. Reflection allows you to learn things about the car without actually opening the box. You can find out the color of the car, how many wheels it has, and even what sounds it can make when you push it.
Similarly, in programming, sometimes programmers have objects (like the toy car) that they can't see directly. But with the help of reflection, they can still learn a lot about those objects. They can find out their names, what they can do, and even change their behaviors, all without having to open the box (or directly access the object in their code).
Reflection is like a special tool that lets programmers explore and manipulate objects in their computer programs, just like you can explore and learn about the toy car inside the box using the magic mirror.
How to use reflection to find the two date fields in an employee object and assign today's date to those fields
Code:
using System;
using System.Reflection;
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime JoiningDate { get; set; }
public decimal Salary { get; set; }
public DateTime BirthDate { get; set; }
// ...other properties
}
public class Program
{
public static void Main()
{
Employee employee = new Employee();
UpdateDateFields(employee);
// Print the updated values
Console.WriteLine("Joining Date: " + employee.JoiningDate);
Console.WriteLine("Birth Date: " + employee.BirthDate);
}
public static void UpdateDateFields(object obj)
{
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.PropertyType == typeof(DateTime))
{
property.SetValue(obj, DateTime.Today);
}
}
}
}
Posted on June 27, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.