[ACCEPTED]-Avoid giving namespace name in Type.GetType()-types

Accepted answer
Score: 57

I've used a helper method that searches 6 all loaded Assemblys for a Type matching the specified 5 name. Even though in my code only one Type 4 result was expected it supports multiple. I 3 verify that only one result is returned 2 every time I used it and suggest you do 1 the same.

/// <summary>
/// Gets a all Type instances matching the specified class name with just non-namespace qualified class name.
/// </summary>
/// <param name="className">Name of the class sought.</param>
/// <returns>Types that have the class name specified. They may not be in the same namespace.</returns>
public static Type[] getTypeByName(string className)
{
    List<Type> returnVal = new List<Type>();

    foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
    {
        Type[] assemblyTypes = a.GetTypes();
        for (int j = 0; j < assemblyTypes.Length; j++)
        {
            if (assemblyTypes[j].Name == className)
            {
                returnVal.Add(assemblyTypes[j]);
            }
        }
    }

    return returnVal.ToArray();
}
Score: 19

There is no need to complicate things.

AppDomain.CurrentDomain
    .GetAssemblies()
    .SelectMany(x => x.GetTypes())
    .FirstOrDefault(t => t.Name == "MyTypeName");

Use 1 Where instead of FirstOrDefault to get all the results.

Score: 0

Simple Cached version

Do this once....

        nameTypeLookup = typeof(AnyTypeWithin_SomeNamespace).Assembly
            .DefinedTypes.Where(t => t.DeclaringType == null)
            .ToDictionary(k => k.Name, v => v);

Usage 1 - lookup many times via dictionary

nameTypeLookup["TheClass"];

More Related questions