C# - Reflection

The .Net Framework provides a reflection capability that allows you to obtain information about assemblies, modules and types as well as being able to dynamically create instances of types. In this article, I explain how to get type information and create instances dynamically. Let's start with a simple example with an existing .Net class. Consider at run-time, you want to get a list of class properties. To achieve this, we must first import the System.Reflection namespace. Once imported the Type class can be used to get details about a class using the GetType() method as seen in the example below.
  1. using System;  
  2. using System.Reflection;  
  3.  
  4. class Program  
  5. {  
  6.     static void Main(string[] args)  
  7.     {  
  8.         PropertyInfo[] propInfoList = Type.GetType("System.DateTime").GetProperties();  
  9.  
  10.         foreach (PropertyInfo propInfo in propInfoList)  
  11.         {  
  12.             Console.WriteLine(propInfo.Name);  
  13.         }  
  14.  
  15.         Console.ReadKey();  
  16.     }  
  17. } 
In the above code the GetProperties() method will return an array of PropertyInfo objects for the System.DateTime Type. The PropertyInfo class has a Name property, which will return the public property name of the reflecting class. To get a list of non public properties, you can use a bitmask comprised of System.Reflection.BindingFlags as shown in the example below.
  1. PropertyInfo[] propInfoList = Type.GetType("System.DateTime").GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
We can also use the GetMethod() method to get a list of public methods.
  1. MethodInfo[] methodInfoList = Type.GetType("System.DateTime").GetMethods();  
  2.  
  3. foreach (MethodInfo methodInfo in methodInfoList)  
  4. {  
  5.     Console.WriteLine(methodInfo.Name);  
  6. } 
BindingFlags can also be used to get a list of non public methods. Reflection can also be used to get a list of all class attributes using the GetCustomAttributes() method.
  1. object[] attrs = Type.GetType("System.String").GetCustomAttributes(true);  
  2.  
  3. foreach (Attribute attr in attrs)  
  4. {  
  5.     Console.WriteLine(attr.ToString());  
  6. } 
You can also filter the attributes if you need to find a particular attribute.
  1. object[] attrs = Type.GetType("System.String").GetCustomAttributes(Type.GetType("System.SerializableAttribute")true)

No comments:

Post a Comment