Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Namespace of an Assembly?

Consider i have an assembly(class library dll) which i have loaded using the following code,

Assembly a = Assembly.LoadFrom(@"C:\Documents and Settings\E454935\My Documents\Visual Studio 2005\Projects\nunit_dll_hutt\for_hutt_proj\bin\Debug\asdf.dll");    

and i need to get the type of the Assembly. In order to get the type i need the namespace of the assembly.

Type t = asm.GetType("NAMESPACE.CLASSNAME",false,true);              

how can i get the Namespace in the above line.?! as inorder to get the Namespace, i need to get the type..?

Type.Namespace; 

i.e i need to get the Namespace of the assembly which can be used to get its Type.

Thanks in advance

like image 603
SyncMaster Avatar asked Mar 17 '09 05:03

SyncMaster


People also ask

How to find assembly of a namespace in c#?

Type t = asm. GetType("NAMESPACE. CLASSNAME",false,true);

Which namespace helps to find information of an assembly?

Reflection Namespace. Represents an assembly, which is a reusable, versionable, and self-describing building block of a common language runtime application. This class contains a number of methods that allow you to load, investigate, and manipulate an assembly.

What is name space and assembly?

In brief, a namespace is a logical group of related classes that can be used by the languages targeted by Microsoft . NET framework, while an assembly is a building block of . NET Framework applications that form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions.


2 Answers

Use

Assembly.GetTypes(); 

This will get you a collection of all types and then you can get the Namespace property for each of them.

Then I guess you can simply check that all the types have same Namespace value and use this value. Otherwise add some other logic to detect what namespace to consider primary.

like image 163
sharptooth Avatar answered Sep 21 '22 12:09

sharptooth


An assembly can contain multiple namespaces. I think what you really want to ask is how to get a type from an assembly without specifying the namespace.

I don't know if there is a better way, but you can try looking for the specific type like this (add - using linq;):

myassembly.GetTypes().SingleOrDefault(t => t.Name == "ClassName") 

This will effectively throw if there is more than 1 class with that name under different namespaces (because the Single method ensures there is only 1).

For a list of the namespaces for that class you can:

Assembly.Load("ClassName").GetTypes().Select(t => t.Namespace).Distinct(); 
like image 37
eglasius Avatar answered Sep 25 '22 12:09

eglasius