Using Type.Assembly
to get the current assembly is nearly free in terms of performance; it’s a simple property access. On the other
hand, Assembly.GetExecutingAssembly()
can take up to 30 times as long because it walks up the call stack to find the assembly.
Note that Assembly.GetExecutingAssembly()
is different than Type.Assembly
because it dynamically returns the assembly
that contains the startup object of the currently executed application. For example, if executed from an application it will return the application
assembly, but if executed from a unit test project it could return the unit test assembly. Type.Assembly
always returns the assembly that
contains the specified type.
Noncompliant code example
public class Example
{
public static void Main()
{
Assembly assem = Assembly.GetExecutingAssembly(); // Noncompliant
Console.WriteLine("Assembly name: {0}", assem.FullName);
}
}
Compliant solution
public class Example
{
public static void Main()
{
Assembly assem = typeof(Example).Assembly; // Here we use the type of the current class
Console.WriteLine("Assembly name: {0}", assem.FullName);
}
}