Every once and awhile I find the need to get a reference to a Type maintained in a separate assembly. This tends to happen when I am loading assemblies at runtime and am trying to build an instance of a known Type in that assembly. In fact, this is how my XmlProvider class builds instances. Well I have found that the built in System.Reflection.Emit.TypeBuilder.GetType(…) method does not deal well with these advanced situations. So here is a very inefficient, brute force method for getting the Type object you need. Also note that I have included some tags for cross-platform compatibility. I am still looking for a workaround for the Zune and Xbox 360.
///
/// Handles cross assembly type referencing by searching loaded assemblies for a type.
///
public static class TypeBuilder
{
public static Type[] GetBaseTypes(Type type)
{
List types = new List();
Type t = type;
while (t.BaseType != null)
{
if (t.BaseType == typeof(Object))
break;
types.Add(t.BaseType);
t = t.BaseType;
}
return types.ToArray();
}
///
/// Gets the Type object for a specific type name.
///
///
The type name to search.
/// A Type object.
/// Searches assemblies only loaded in the current application domain.
///
public static Type GetType(string typeName)
{
#if ZUNE
return null;
#else
if (String.IsNullOrEmpty(typeName))
throw new ArgumentException("Provided type name was invalid.");
// Get a list of assemblies first...
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
// Loop through until we find the type.
foreach (Assembly assembly in assemblies)
{
Type t = assembly.GetType(typeName);
if (t == null)
{
Type[] ts = assembly.GetTypes();
foreach (Type type in ts)
if (type.Name == typeName || type.AssemblyQualifiedName == typeName)
return type;
}
if (t != null)
return t;
}
// We may need to fall back on the built in builder.
return System.Reflection.Emit.TypeBuilder.GetType(typeName);
#endif
}
}