How can I get all classes within a namespace in C#?
3 Answers
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);
}
For anything before .Net 2.0 where Assembly.GetExecutingAssembly() is not available, you will need a small workaround to get the assembly:
Assembly myAssembly = typeof(<Namespace>.<someClass>).GetTypeInfo().Assembly;
Type[] typelist = GetTypesInNamespace(myAssembly, "<Namespace>");
for (int i = 0; i < typelist.Length; i++)
{
Console.WriteLine(typelist[i].Name);
}
-
2.Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal) Jun 4, 2009 at 8:40
-
9Also, keep in mind that Assembly != namespace - some namespaces are spread across multiple assemblies.– BevanJun 4, 2009 at 8:41
-
1and 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. Jun 4, 2009 at 8:44
-
2Good 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 :) Jun 4, 2009 at 8:55
-
4I think foreach is just easier to look at personally. Behind the scenes the two loops are pretty much the same in regards to performance. Jun 8, 2011 at 16:59
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)
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.