In .Net, reflection is the process of finding runtime type. That means using reflection you can find metadata about the types defined in your program. Today we discuss about reflection with simple example.
To get the metadata .Net provides System.Reflection namespace. Under this namespace we have several classes to help us in finding the metadata.
Create simple class Company as shown below.
namespace CSharpReflection
{
class Company
{
public int cRegNo = 123456;
public string CompanyName { get; set; }
public string GetCompanyAddress()
{
return "Address";
}
}
}
As shown above, Company class one variable cRegNo, one property CompanyName and one method GetCompanyAddress().
Now we will write the code to find out what are the variables, properties and methods Company class has as shown below.
using System;
using System.Reflection;
namespace CSharpReflection
{
class Program
{
static void Main(string[] args)
{
Company objCompany = new Company();
Type type = objCompany.GetType();
//find methods in the Company class
MethodInfo[] mi = type.GetMethods();
foreach (MethodInfo m in mi)
Console.WriteLine("Method Name: " + m.Name + " ; Return Type: " + m.ReturnType);
//find Properties in the Company class
PropertyInfo[] PIs = type.GetProperties();
foreach (PropertyInfo pi in PIs)
Console.WriteLine("Property Name: " + pi.Name + " ; Property Type: " + pi.PropertyType);
//find Fields in the Company class
FieldInfo[] FIs = type.GetFields();
foreach (FieldInfo fi in FIs)
Console.WriteLine("Field Name: " + fi.Name + " ; Field Type: " + fi.FieldType);
Console.ReadLine();
}
}
}
As shown above we created the object for Company class and assigning its type to Type clas variable types by using GetType() method. From this Type variable type we are getting all methods info by using GetMethods() method, properties info by using GetProperties() method and Fields info by using GetFields() method.
Once you execute the application, the output is as shown below.
Reflection is useful whenever you want to know methods, fields, properties...etc info of a class for which you don't have direct access.