JSEDLAK » Reflection

Posts Tagged ‘Reflection’

Getting A Type Cross-Assembly

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.

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/// <summary>
/// Handles cross assembly type referencing by searching loaded assemblies for a type.
/// </summary>
public static class TypeBuilder
{
    public static Type[] GetBaseTypes(Type type)
    {
        List<Type> types = new List<Type>();
 
        Type t = type;
        while (t.BaseType != null)
        {
            if (t.BaseType == typeof(Object))
                break;
 
            types.Add(t.BaseType);
 
            t = t.BaseType;
        }
 
        return types.ToArray();
    }
 
    /// <summary>
    /// Gets the Type object for a specific type name.
    /// </summary>
    /// <param name="typeName">The type name to search.</param>
    /// <returns>A Type object.</returns>
    /// <remarks>Searches assemblies only loaded in the current application domain.</remarks>
    /// <seealso cref="System.Reflection.Emit.TypeBuilder"/>
    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
    }
}