When iterating through a set of assemblies, e.g. AppDomain.CurrentDomain.GetAssemblies(), dynamic assemblies will throw a NotSuportedException if you try to access properties li
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)
In .NET 4 you can also check the Assembly.IsDynamic property.
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;
}
}