Diego Mijelshon
Diego Mijelshon

Reputation: 52745

Determining if a .NET type is dynamic (created using Reflection.Emit)

While the .NET 4 framework provides the Assembly.IsDynamic method, that's not the case with .NET 2.0/3.5.

The use case is simple: for logging purposes, I want to determine the underlying type name of an entity that might be wrapped by a dynamic proxy without having any references to NHibernate or Castle (which know about the proxy)

For example, I might have a CatProxYadaYada, but I'm interested in Cat.

What's the easiest way to get that type? I was thinking of this skeleton:

var type = obj.GetType();
while (IsProxy_Dynamic_Whatever(obj))
  type = type.BaseType;
return type;

Upvotes: 2

Views: 803

Answers (1)

Aaronaught
Aaronaught

Reputation: 122624

If the assembly was generated using Emit, then you should be able to verify this by checking if the type's assembly is an AssemblyBuilder. In other words, something like this:

static Type GetNonEmittedType(Type t)
{
    if (t.Assembly is AssemblyBuilder)
        return GetNonEmittedType(t.BaseType);
    return t;
}

This might not work for every kind of dynamic proxy - it really depends on how it was generated. But it works with Emit.

Upvotes: 3

Related Questions