Reflection
1.Reflection can be used for type discovery (i.e finding methods, properties, events, fields, constructors etc) and late binding.
2.When we drag and drop a button from toolbox in visual studio, vs uses reflection to get all properties of button class.
3.Late binding can be achieved by using reflection. You can use reflection to dynamically create an instance of a type, about which we don't have any information at compile time.
Example:
class Program
{
static void Main(string[] args)
{
//Type t = Type.GetType("ReflectionExp.Customer");
Type t = typeof(ReflectionExp.Employee);
PropertyInfo[] propInfo = t.GetProperties();
// Print the list of Methods
Console.WriteLine("Methods in Employee Class");
MethodInfo[] methods = t.GetMethods();
foreach (MethodInfo method in methods)
{
// Print the Return type and the name of the method
Console.WriteLine(method.ReturnType.Name + " " + method.Name);
}
Console.WriteLine();
// Print the Properties
Console.WriteLine("Properties in Employee Class");
foreach(PropertyInfo prop in propInfo)
{
Console.WriteLine(prop.Name + " " + prop.PropertyType.Name + " " + prop.ReflectedType);
}
Console.WriteLine();
// Print the Constructors
Console.WriteLine("Constructors in Employee Class");
ConstructorInfo[] constructors = t.GetConstructors();
foreach (ConstructorInfo constructor in constructors)
{
Console.WriteLine(constructor.ToString());
}
Console.Read();
}
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public Employee(int ID, string Name)
{
this.Id = ID;
this.Name = Name;
}
public Employee()
{
this.Id = -1;
this.Name = string.Empty;
}
public void PrintID()
{
Console.WriteLine("ID = {0}", this.Id);
}
public void PrintName()
{
Console.WriteLine("Name = {0}", this.Name);
}
}