Home
Browse all 647 examples
Download all 647 examples
Download sample chapters
Reviews
Errata
Acknowledgments
Links on .NET
Paradoxal Press

Buy directly from Paradoxal Press at $33.99 (Save 43%)



Category: Programming
Level: Beginner to seasoned
900 pages
ISBN-10 097661322-0
ISBN-13 978-097661322-0
$59.99 USA
$79.99 CANADA


Listing 7-2 extracted from chapter Reflection, late binding, attributes


Listing 7-1<     > Listing 7-3


This listing can be compiled with the command line:
csc.exe /target:exe Example_7_2.cs
Errors: 0 Warnings: 0


Example_7_2.cs
using System;
using System.Reflection;
class Program {
   static void Main() {
      // Build the strong name of the 'System' assembly.
      // Its version number is the same as the one of the assembly
      // 'mscorlib' which contains the System.Object class.
      string systemAsmStrongName = "System, Culture = neutral, " +
         "PublicKeyToken=b77a5c561934e089, Version=" +
         typeof(System.Object).Assembly.GetName().Version.ToString();

      // Explicitly load the 'System' assembly for reflecting on it.
      // There is no need to load the 'mscorlib' assembly since
      // it is automatically and implicitly loaded by the CLR.
      Assembly.ReflectionOnlyLoad( systemAsmStrongName );

      // For each assembly in the current AppDomain...
      foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) {
         Console.WriteLine("\nAssembly:" + a.GetName().Name);

         // For each type in the assembly 'a'...
         foreach (Type t in a.GetTypes()) {
            // Treat only public classes...
            if (!t.IsClass || !t.IsPublic) continue;
            bool bDerivedException = false;
            bool bDirectInherit = true;

            // Is System.Exception a base type of 't'?
            Type baseType = t.BaseType;
            while ( baseType != null && !bDerivedException ) {
               // To find attribute classes replace the following line 
               // by:  if( baseType == typeof(System.Attribute))
               if ( baseType == typeof(System.Exception) )
                  bDerivedException = true;
               else bDirectInherit = false;
               baseType = baseType.BaseType;
            }// end while

            // Display the name of the class if it is an exception
            // class. Put a star if the class doesn't inherit directly
            // from System.Exception.
            if ( bDerivedException )
               if ( bDirectInherit )
                  Console.WriteLine( "  " + t );
               else
                  Console.WriteLine( "  *" + t );
         }// end foreach(Type...
      }// end foreach(Assembly...
   }// end Main
}	
Copyright Patrick Smacchia 2006 2007