Pages

Wednesday, April 22, 2009

Using Reflection in C#

One neat purpose for reflection is to see what assemblies the application loads, and also see
information of them. It can be useful for debugging and error reporting purposes.

Below is an example how to use it:

    1 using System;
    2 using System.Reflection;
    3 
    4 namespace ReflectionTest
    5 {
    6   class ReflectionTester
    7   {
    8     static void Main(string[] args)
    9     {
   10       GetAssemblies();
   11       Console.ReadLine();
   12     }
   13 
   14     public static void GetAssemblies()
   15     {
   16       Assembly[] appAssemblies =
   17         System.AppDomain.CurrentDomain.GetAssemblies();
   18 
   19       foreach (Assembly assembly in appAssemblies)
   20       {
   21         Console.WriteLine(assembly.FullName);
   22       }
   23     }
   24   }
   25 }

Code outputs used assemblies and various information about them, like:

mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Microsoft.VisualStudio.HostingProcess.Utilities, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a


Further reading:
MSDN Reflection (C# Programming Guide)

No comments:

Post a Comment