get assembly by class name

Viewed 35093

Is there any way to get the assembly that contains a class with name TestClass? I just know the class name, so I can't create an instance of that. And

Type objectType = assembly.GetType("TestClass");

didn't work for me.

4 Answers

Marc's answer is really good, but since it was too slow (I'm using that method often), I decided to go with a different approach:

    private static Dictionary<string, Type> types;
    private static readonly object GeneralLock = new object();

    public static Type FindType(string typeName)
    {
        if (types == null)
        {
            lock (GeneralLock)
            {
                if (types == null)
                {
                    types = new Dictionary<string, Type>();
                    var appAssemblies = AppDomain.CurrentDomain.GetAssemblies();
                    foreach (var appAssembly in appAssemblies)
                    {
                        foreach (var type in appAssembly.GetTypes())
                            if (!types.ContainsKey(type.Name))
                                types.Add(type.Name, type);
                    }
                }
            }
        }

        return types[typeName];
    }

You can handle the name clash the way you want, but in this example I decided to just ignore the subsequent ones.

Related