views:

1470

answers:

3

Possible Duplicates

Excuse me. How to get all classes within namespace?

A: 

With Reflection you cal loop through all the types in an assembly. A type has a Namespace property which you use to filter only the namespace you're interested in.

Gerrie Schenck
+1  A: 

You'll need to provide a little more information...

Do you mean by using Reflection. You can iterate through an assemblies Manifest and get a list of types using

   System.Reflection.Assembly myAssembly = Assembly.LoadFile("");

   myAssembly.ManifestModule.FindTypes()

If it's just in Visual Studio, you can just get the list in the intellisense window, or by opening the Object Browser (CTRL+W, J)

Eoin Campbell
+8  A: 

You will need to do it "backwards"; list all the types in an assembly and then checking the namespace of each type:

using System.Reflection;
private Type[] GetTypesInNamespace(Assembly assembly, string nameSpace)
{
    return assembly.GetTypes().Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)).ToArray();
}

Example of usage:

Type[] typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyNamespace");
for (int i = 0; i < typelist.Length; i++)
{
    Console.WriteLine(typelist[i].Name);
}
Fredrik Mörk
.Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)
abatishchev
Also, keep in mind that Assembly != namespace - some namespaces are spread across multiple assemblies.
Bevan
and why not to return just a IEnumerable<Type>? All the more, you do an enumeration between the results, also 'foreach' instead of 'for' is better, I think.
abatishchev
Good comments, thanks for that. By making the return type to an IEnumerable<Type> eliminates the need for the last ToArray call. Not sure if I agree that 'foreach' is better than 'for' though; as I see it the performance difference is neglectible so I think it comes down to personal style. But may have a good argument for preferring 'foreach'; if so feel free to share it; I like to be proven wrong :)
Fredrik Mörk