When iterating through a set of assemblies, e.g. AppDomain.CurrentDomain.GetAssemblies(), dynamic assemblies will throw a NotSuportedException if you try to access properties like CodeBase. How can you tell that an assembly is dynamic without triggering and catching the NotSupportedException?
3 Answers
To check if the assembly is dynamic:
if (assembly.ManifestModule is System.Reflection.Emit.ModuleBuilder)
This took me a while to figure out, so here it is asked and answered.
Update:
In .NET 4.0, there is now a property:
if (assembly.IsDynamic)

- 9,338
- 5
- 44
- 79

- 5,256
- 3
- 29
- 33
-
6Not quite correct. A modulebuilder can be 'non-dynamic'. You should use `ModuleBuilder.IsTransient` to check for 'dynamic'. – leppie Jun 30 '11 at 10:41
In .NET 4 you can also check the Assembly.IsDynamic property.

- 822
- 8
- 16
-
Finally Microsoft has provided this :) This is obviously the way to go from now on. – Mike Stockdale Jul 01 '11 at 03:26
Prior to .NET Framework 4, the simplest solution seems to be to check if the Assembly is of type System.Reflection.Emit.AssemblyBuilder. This is the solution we use on our team.
If you take a look at the AssemblyBuilder's CodeBase property implementation, it simply throws an exception, regardless of anything else. AssemblyBuilder is also a sealed class, so it's impossible for a derived class to change this behavior. So, if you have an AssemblyBuilder object, you can be certain that you can never call CodeBase or GetManifestResourceStream or a bunch of other methods.
public override string CodeBase
{
get
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
}
}
And in .NET Framework 4, checking the Assembly.IsDynamic property should be preferable because it's more legible and perhaps more future-proof, in case some new class comes along that overrides IsDynamic. Since AssemblyBuilder.IsDynamic always returns true, this is more evidence that an AssemblyBuilder object is always equivalent to a "dynamic dll".
Here's the .NET 4 AssemblyBuilder's IsDynamic:
public override bool IsDynamic
{
get {
return true;
}
}

- 1,888
- 20
- 25