C#

C# Reflection – What is Assembly?

Assembly is the main unit in .NET applications. Assembly is a collection of types and its information. There are two types of assemblies:

  1. Executable files (EXE)
  2. Libraries (DLL)

Both type of assemblies includes information about types and its members in its metadata.

There are three ways to get Assembly instances:

  1. Getting assembly instance from type information
  2. Getting assembly instance from current assembly and parent assembly
  3. Loading assembly instance from disk

1. Getting assembly instance from type information

We can pass reference to an already created object like this:

Program p = new Program();
Assembly assembly = p.GetType().Assembly;

We can also get assembly instance by giving the class name.

Assembly assembly = typeof(Program).Assembly;

2. Getting assembly instance from current assembly and parent assembly

Currently executing assembly instance

Console.WriteLine(Assembly.GetExecutingAssembly());

For getting the first executable assembly which contains the Main method by which the application starts:

Assembly.GetEntryAssembly();

For getting the instance of parent assembly which called current assembly:

Assembly.GetCallingAssembly();

3. Loading assembly instance from disk

Assembly a = Assembly.LoadFile(@"C:\ReflectionLibrary.DLL");

Assembly important properties and methods

Assembly class provides various properties to get useful information about the assembly. Below is the list of some useful properties.

PropertiesDescription
CodebaseReturns the location of the assembly.
EntryPointReturns the method information of the entry methods (Main method). Console applications returns reference to the Main method and dynamic link libraries (DLL) returns NULL.
FullNameReturns the full name of the assembly including version number, Culture and PublicKeyToken.
GlobalAssemblyCacheBool property. Returns true if assembly loaded from GAC else returns false.
CustomAttributesReturns all the custom attributes of the assembly.
DefinedTypesReturns all the types in the assembly.
ModulesReturn all the modules in the assembly.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.