How can I get all classes within a namespace?

C#.NetReflectionNamespaces

C# Problem Overview


How can I get all classes within a namespace in C#?

C# Solutions


Solution 1 - C#

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);
}

Solution 2 - C#

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)

Solution 3 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMicheal sonnalView Question on Stackoverflow
Solution 1 - C#Fredrik MörkView Answer on Stackoverflow
Solution 2 - C#Eoin CampbellView Answer on Stackoverflow
Solution 3 - C#Gerrie SchenckView Answer on Stackoverflow