views:

2021

answers:

4

In .Net, given a type name, is there a method that tells me in which assembly (instance of System.Reflection.Assembly) that type is defined?

I assume that my project already has a reference to that assembly, just need to know which one it is.

+1  A: 
Type.GetType(typeNameString).Assembly
John Saunders
That methods expects an assembly-qualified name. Are you sure it works cross-assembly if you don't qualify it with the assembly name?
chakrit
+7  A: 
Assembly.GetAssembly(typeof(System.Int32))

Replace System.Int32 with whatever type you happen to need. Because it accepts a Type parameter, you can do just about anything this way, for instance:

string GetAssemblyLocationOfObject(object o) {
    return Assembly.GetAssembly(o.GetType()).Location;
}
Matthew Scharley
As a sidenote, I use that exact function as a way of populating the ReferencedAssemblies list when using the CSharpCodeProvider to compile C# dynamically.
Matthew Scharley
+5  A: 

Assembly.GetAssembly assumes you have an instance of the type, and Type.GetType assumes you have the fully qualified type name which includes assembly name.

If you only have the base type name, you need to do something more like this:

public static String GetAssemblyNameContainingType(String typeName) 
{
 foreach (Assembly currentassembly in AppDomain.CurrentDomain.GetAssemblies()) 
 {
  Type t = currentassembly.GetType(typeName, false, true);
  if (t != null) {return currentassembly.FullName;}
 }

 return "not found";
}

This also assumes your type is declared in the root. You would need to provide the namespace or enclosing types in the name, or iterate in the same manner.

jpj625
I'd probably throw an ArgumentException in the case it can't find what you're looking for. Presumably that would be the exceptional case, and then you could also assume you found it (or put error handling code in a catch statement)
Matthew Scharley
BUT, Assembly.GetAssembly doesn't need an instance of the type, it only needs the type, so if you're looking for something that you know the type at compile-time, you can use typeof(Type) like in my first example.
Matthew Scharley
Thanks for the answers, it's working like a charm for me. I didn't have the Type, just the type name and know that a reference to an assembly containing it was available.
Fabio de Miranda
+1  A: 

If you can use it, this syntax is the shortest/cleanest:

typeof(int).Assembly
280Z28