tags:

views:

94

answers:

3

is there any way to get the assembly that contains a class with name TestClass. i just know the class name,so i cant create instance of that. and Type objectType = assembly.GetType("TestClass"); didnt work for me

+2  A: 
Assembly asm = typeof(TestClass).Assembly;

will get you the assembly as long as it is referenced. Otherwise, you would have to use a fully qualified name:

Assembly asm = null;
Type type = Type.GetType("TestNamespace.TestClass, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
if (type != null)
{
    asm = type.Assembly;
}
0xA3
+3  A: 

From the Type objectType in the question, I assume you are actually after the type by name (not the assembly); so assuming the assembly is loaded and the type name is unique, LINQ may help:

Type objectType = (from asm in AppDomain.CurrentDomain.GetAssemblies()
                   from type in asm.GetTypes()
                   where type.IsClass && type.Name == "TestClass"
                   select type).Single();
object obj = Activator.CreateInstance(objectType);

However, it may be better to work with the assembly-qualified name instead of the type name.

Marc Gravell
+2  A: 

Actually knowledge of classname is enough in most scenarios. MSDN says - If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

Type neededType = Type.GetType("TestClass"); //or typeof(TestClass) 
Assembly a = neededType.Assembly;

In case you dont know the assembly containing type (though i cant imagine why) -

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
Asssembly result = assemblies.FirstOrDefault(a=>a.GetType("TestClass",false)!=null);

The only restriction - assembly containing TestClass should have been already loaded at the moment of calling such code.

Hope this'll help. :)

ProfyTroll