What is Reflection?
Reflection lets you inspect and use classes, methods, properties at runtime — even if you don’t know them at compile time.
✅ Example: Get Class Info at Runtime
using System;
using System.Reflection;
class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public void Display()
{
Console.WriteLine("Employee Display Method");
}
}
class Program
{
static void Main()
{
Type type = typeof(Employee);
Console.WriteLine("Class Name: " + type.Name);
Console.WriteLine("\nProperties:");
foreach (PropertyInfo prop in type.GetProperties())
{
Console.WriteLine(prop.Name);
}
Console.WriteLine("\nMethods:");
foreach (MethodInfo method in type.GetMethods())
{
Console.WriteLine(method.Name);
}
}
}
➕ Extension Method Example
What is an Extension Method?
Allows you to add methods to existing classes without modifying them.
✅ Example: Extend string class
Step 1: Create Extension Class
using System;
static class StringExtensions
{
public static bool IsEmail(this string value)
{
return value.Contains("@") && value.Contains(".");
}
}
Step 2: Use Extension Method
class Program
{
static void Main()
{
string email = "test@gmail.com";
bool result = email.IsEmail();
Console.WriteLine(result);
}
}
0 Comments
POST Answer of Questions and ASK to Doubt