Friday, July 16, 2010

Reflection in C#

There are several scenarios in C# that reflection comes into use
  • Every time we use "is" and "as" operators
  • Every time we use data bindings for user controls
  • The ValueType.Equals and ValueType.operator== are implemented using reflection only
  • Serialization uses reflection
And several other scenarios, but there is one interesting case that is not well-known and that is when we write unit tests. There are situations where we want to write a unit test for a function that is private to a class, this is where we can use reflection to get access to that function and call it. Here is a sample code that we can use to access a private static member of a class, the same routine can be used to invoke a private member function(The difference is that for static members we don't need instantiation )
 try {   System.Reflection.Assembly assembly =  Assembly.LoadFile(/*Path*/);    Console.WriteLine("Full Name:{0}\nName:{1}\nMajor Version:{2}\n                             Minor Version:{3}\nCodeBase:{4}"  , assembly.FullName  , assembly.GetName().Name  , assembly.GetName().Version.Major  , assembly.GetName().Version.Minor  , assembly.CodeBase);    Type[] allTypes = assembly.GetTypes();   foreach (Type type in allTypes)   {  FieldInfo[] fieldInfos = type.GetFields(                BindingFlags.Static | BindingFlags.NonPublic);  foreach (FieldInfo fieldInfo in fieldInfos)  {    Console.WriteLine("Field name:{0}                                   , Declaring Type:{1}                                   , Filed Type:{2}                                   , Static:{3}"                 , fieldInfo.Name                 , fieldInfo.DeclaringType.ToString()                 , fieldInfo.FieldType                 , fieldInfo.IsStatic);     if (fieldInfo.IsStatic)    {      Console.WriteLine("Static = {0}"                      , fieldInfo.GetValue(null));      fieldInfo.SetValue(null                      , 200);             Console.WriteLine("Static = {0}"                      , fieldInfo.GetValue(null));    }        }   }   Console.WriteLine("Done Loading Assembly"); } catch (Exception exception) {   Console.WriteLine(exception.Message); }

No comments:

Post a Comment