BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Reflection
.NET 1.1+

Reflecting Assembly Information

The seventeenth part of the Reflection tutorial looks at how information about assemblies can be obtained using reflection. This is an important prerequisite for more advanced reflection techniques, such as dynamically loading assemblies at run time.

Assembly Properties

As with other reflection classes, Assembly contains a number of properties that provide information about the assembly itself. Four common properties are:

  • FullName. Returns a string containing the full name of the assembly. This includes the name, the version, culture information and public key token details.
  • Location. Returns a string containing the file system path of the assembly file.
  • ImageRuntimeVersion. Returns a string containing the version number of the common language runtime (CLR)used in the assembly.
  • EntryPoint. For executable files, this returns a MethodInfo object that represents the entry point method for the assembly. When executed against assemblies that do not include an entry point, such as DLLs, the method returns null.

The following sample code shows an example output for these properties. In this example the assembly was compiled for .NET 4.0.

Assembly asm = Assembly.GetExecutingAssembly();
Console.WriteLine(asm.FullName);
Console.WriteLine(asm.Location);
Console.WriteLine(asm.ImageRuntimeVersion);
Console.WriteLine(asm.EntryPoint);

/* OUTPUT

AssemblyReflection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
C:\AssemblyReflection\AssemblyReflection\bin\Debug\AssemblyReflection.exe
v4.0.30319
Void Main(System.String[])

*/

Obtaining the Types in an Assembly

Generally, the primary reason for reflecting over an assembly is to obtain references to the types that it contains. You can then examine those types and invoke their members. Two methods are provided by the Assembly class that allow you to generate Type instances for the contained classes. The first of these is GetTypes. This returns an array of Type objects, each representing one of the types in the assembly. All public and non-public types are returned.

Assembly asm = Assembly.GetExecutingAssembly();
Type[] types = asm.GetTypes();

Console.WriteLine(types.Length);
Console.WriteLine(types[0].Name);

/* OUTPUT

1
Program

*/

When you only need the details of a specific type you can use GetType. As a minimum, you must provide a string argument containing the name of the type that you wish to reflect. You can also add parameters that determine whether an exception should be thrown for non-existent types and whether the search for the type should be case-sensitive or not. The method returns a Type instance.

Assembly asm = Assembly.GetExecutingAssembly();
Type type = asm.GetType("AssemblyReflection.Program");
10 July 2012