Determining if a .NET type is dynamic (created using Reflection.Emit)
While .NET 4 provides a method Assembly.IsDynamic
, this is not the case for .NET 2.0 / 3.5.
The use case is simple: for logging purposes, I want to define the base name of an object type that can be wrapped with a dynamic proxy without having links to NHibernate or Castle (which know about proxies)
For example, I may have CatProxYadaYada
, but I'm interested Cat
.
What's the easiest way to get this type? I thought about this skeleton:
var type = obj.GetType();
while (IsProxy_Dynamic_Whatever(obj))
type = type.BaseType;
return type;
a source to share
If the assembly was generated with Emit
, you should check this by checking if the assembly is of type AssemblyBuilder
. In other words, something like this:
static Type GetNonEmittedType(Type t)
{
if (t.Assembly is AssemblyBuilder)
return GetNonEmittedType(t.BaseType);
return t;
}
This may not work for every type of dynamic proxy - it really depends on how it was generated. But it works with Emit
.
a source to share