[c#] Getting all types in a namespace via reflection

How do you get all the classes in a namespace through reflection in C#?

This question is related to c# .net reflection namespaces

The answer is


You won't be able to get all types in a namespace, because a namespace can bridge multiple assemblies, but you can get all classes in an assembly and check to see if they belong to that namespace.

Assembly.GetTypes() works on the local assembly, or you can load an assembly first then call GetTypes() on it.


using System.Reflection;
using System.Collections.Generic;
//...

static List<string> GetClasses(string nameSpace)
{
    Assembly asm = Assembly.GetExecutingAssembly();

    List<string> namespacelist = new List<string>();
    List<string> classlist = new List<string>();

    foreach (Type type in asm.GetTypes())
    {
        if (type.Namespace == nameSpace)
            namespacelist.Add(type.Name);
    }

    foreach (string classname in namespacelist)
        classlist.Add(classname);

    return classlist;
}

NB: The above code illustrates what's going on. Were you to implement it, a simplified version can be used:

using System.Linq;
using System.Reflection;
using System.Collections.Generic;
//...

static IEnumerable<string> GetClasses(string nameSpace)
{
    Assembly asm = Assembly.GetExecutingAssembly();
    return asm.GetTypes()
        .Where(type => type.Namespace == nameSpace)
        .Select(type => type.Name);
}

Here's a fix for LoaderException errors you're likely to find if one of the types sublasses a type in another assembly:

// Setup event handler to resolve assemblies
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);

Assembly a = System.Reflection.Assembly.ReflectionOnlyLoadFrom(filename);
a.GetTypes();
// process types here

// method later in the class:
static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
    return System.Reflection.Assembly.ReflectionOnlyLoad(args.Name);
}

That should help with loading types defined in other assemblies.

Hope that helps!


using System.Reflection;
using System.Collections.Generic;
//...

static List<string> GetClasses(string nameSpace)
{
    Assembly asm = Assembly.GetExecutingAssembly();

    List<string> namespacelist = new List<string>();
    List<string> classlist = new List<string>();

    foreach (Type type in asm.GetTypes())
    {
        if (type.Namespace == nameSpace)
            namespacelist.Add(type.Name);
    }

    foreach (string classname in namespacelist)
        classlist.Add(classname);

    return classlist;
}

NB: The above code illustrates what's going on. Were you to implement it, a simplified version can be used:

using System.Linq;
using System.Reflection;
using System.Collections.Generic;
//...

static IEnumerable<string> GetClasses(string nameSpace)
{
    Assembly asm = Assembly.GetExecutingAssembly();
    return asm.GetTypes()
        .Where(type => type.Namespace == nameSpace)
        .Select(type => type.Name);
}

Here's a fix for LoaderException errors you're likely to find if one of the types sublasses a type in another assembly:

// Setup event handler to resolve assemblies
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);

Assembly a = System.Reflection.Assembly.ReflectionOnlyLoadFrom(filename);
a.GetTypes();
// process types here

// method later in the class:
static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
    return System.Reflection.Assembly.ReflectionOnlyLoad(args.Name);
}

That should help with loading types defined in other assemblies.

Hope that helps!


Following code prints names of classes in specified namespace defined in current assembly.
As other guys pointed out, a namespace can be scattered between different modules, so you need to get a list of assemblies first.

string nspace = "...";

var q = from t in Assembly.GetExecutingAssembly().GetTypes()
        where t.IsClass && t.Namespace == nspace
        select t;
q.ToList().ForEach(t => Console.WriteLine(t.Name));

Namespaces are actually rather passive in the design of the runtime and serve primarily as organizational tools. The Full Name of a type in .NET consists of the Namespace and Class/Enum/Etc. combined. If you only wish to go through a specific assembly, you would simply loop through the types returned by assembly.GetExportedTypes() checking the value of type.Namespace. If you were trying to go through all assemblies loaded in the current AppDomain it would involve using AppDomain.CurrentDomain.GetAssemblies()


using System.Reflection;
using System.Collections.Generic;
//...

static List<string> GetClasses(string nameSpace)
{
    Assembly asm = Assembly.GetExecutingAssembly();

    List<string> namespacelist = new List<string>();
    List<string> classlist = new List<string>();

    foreach (Type type in asm.GetTypes())
    {
        if (type.Namespace == nameSpace)
            namespacelist.Add(type.Name);
    }

    foreach (string classname in namespacelist)
        classlist.Add(classname);

    return classlist;
}

NB: The above code illustrates what's going on. Were you to implement it, a simplified version can be used:

using System.Linq;
using System.Reflection;
using System.Collections.Generic;
//...

static IEnumerable<string> GetClasses(string nameSpace)
{
    Assembly asm = Assembly.GetExecutingAssembly();
    return asm.GetTypes()
        .Where(type => type.Namespace == nameSpace)
        .Select(type => type.Name);
}

Quite simple

Type[] types = Assembly.Load(new AssemblyName("mynamespace.folder")).GetTypes();
foreach (var item in types)
{
}

You won't be able to get all types in a namespace, because a namespace can bridge multiple assemblies, but you can get all classes in an assembly and check to see if they belong to that namespace.

Assembly.GetTypes() works on the local assembly, or you can load an assembly first then call GetTypes() on it.


Here's a fix for LoaderException errors you're likely to find if one of the types sublasses a type in another assembly:

// Setup event handler to resolve assemblies
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);

Assembly a = System.Reflection.Assembly.ReflectionOnlyLoadFrom(filename);
a.GetTypes();
// process types here

// method later in the class:
static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
    return System.Reflection.Assembly.ReflectionOnlyLoad(args.Name);
}

That should help with loading types defined in other assemblies.

Hope that helps!


Get all classes by part of Namespace name in just one row:

var allClasses = Assembly.GetExecutingAssembly().GetTypes().Where(a => a.IsClass && a.Namespace != null && a.Namespace.Contains(@"..your namespace...")).ToList();

You won't be able to get all types in a namespace, because a namespace can bridge multiple assemblies, but you can get all classes in an assembly and check to see if they belong to that namespace.

Assembly.GetTypes() works on the local assembly, or you can load an assembly first then call GetTypes() on it.


Just like @aku answer, but using extension methods:

string @namespace = "...";

var types = Assembly.GetExecutingAssembly().GetTypes()
    .Where(t => t.IsClass && t.Namespace == @namespace)
    .ToList();

types.ForEach(t => Console.WriteLine(t.Name));

Namespaces are actually rather passive in the design of the runtime and serve primarily as organizational tools. The Full Name of a type in .NET consists of the Namespace and Class/Enum/Etc. combined. If you only wish to go through a specific assembly, you would simply loop through the types returned by assembly.GetExportedTypes() checking the value of type.Namespace. If you were trying to go through all assemblies loaded in the current AppDomain it would involve using AppDomain.CurrentDomain.GetAssemblies()


Following code prints names of classes in specified namespace defined in current assembly.
As other guys pointed out, a namespace can be scattered between different modules, so you need to get a list of assemblies first.

string nspace = "...";

var q = from t in Assembly.GetExecutingAssembly().GetTypes()
        where t.IsClass && t.Namespace == nspace
        select t;
q.ToList().ForEach(t => Console.WriteLine(t.Name));

//a simple combined code snippet 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace MustHaveAttributes
{
  class Program
  {
    static void Main ( string[] args )
    {
      Console.WriteLine ( " START " );

      // what is in the assembly
      Assembly a = Assembly.Load ( "MustHaveAttributes" );
      Type[] types = a.GetTypes ();
      foreach (Type t in types)
      {

        Console.WriteLine ( "Type is {0}", t );
      }
      Console.WriteLine (
         "{0} types found", types.Length );

      #region Linq
      //#region Action


      //string @namespace = "MustHaveAttributes";

      //var q = from t in Assembly.GetExecutingAssembly ().GetTypes ()
      //        where t.IsClass && t.Namespace == @namespace
      //        select t;
      //q.ToList ().ForEach ( t => Console.WriteLine ( t.Name ) );


      //#endregion Action  
      #endregion

      Console.ReadLine ();
      Console.WriteLine ( " HIT A KEY TO EXIT " );
      Console.WriteLine ( " END " );
    }
  } //eof Program


  class ClassOne
  {

  } //eof class 

  class ClassTwo
  {

  } //eof class


  [System.AttributeUsage ( System.AttributeTargets.Class |
    System.AttributeTargets.Struct, AllowMultiple = true )]
  public class AttributeClass : System.Attribute
  {

    public string MustHaveDescription { get; set; }
    public string MusHaveVersion { get; set; }


    public AttributeClass ( string mustHaveDescription, string mustHaveVersion )
    {
      MustHaveDescription = mustHaveDescription;
      MusHaveVersion = mustHaveVersion;
    }

  } //eof class 

} //eof namespace 

Following code prints names of classes in specified namespace defined in current assembly.
As other guys pointed out, a namespace can be scattered between different modules, so you need to get a list of assemblies first.

string nspace = "...";

var q = from t in Assembly.GetExecutingAssembly().GetTypes()
        where t.IsClass && t.Namespace == nspace
        select t;
q.ToList().ForEach(t => Console.WriteLine(t.Name));

As FlySwat says, you can have the same namespace spanning in multiple assemblies (for eg System.Collections.Generic). You will have to load all those assemblies if they are not already loaded. So for a complete answer:

AppDomain.CurrentDomain.GetAssemblies()
                       .SelectMany(t => t.GetTypes())
                       .Where(t => t.IsClass && t.Namespace == @namespace)

This should work unless you want classes of other domains. To get a list of all domains, follow this link.


Namespaces are actually rather passive in the design of the runtime and serve primarily as organizational tools. The Full Name of a type in .NET consists of the Namespace and Class/Enum/Etc. combined. If you only wish to go through a specific assembly, you would simply loop through the types returned by assembly.GetExportedTypes() checking the value of type.Namespace. If you were trying to go through all assemblies loaded in the current AppDomain it would involve using AppDomain.CurrentDomain.GetAssemblies()


For a specific Assembly, NameSpace and ClassName:

var assemblyName = "Some.Assembly.Name"
var nameSpace = "Some.Namespace.Name";
var className = "ClassNameFilter";

var asm = Assembly.Load(assemblyName);
var classes = asm.GetTypes().Where(p =>
     p.Namespace == nameSpace &&
     p.Name.Contains(className) 
).ToList();

Note: The project must reference the assembly


Quite simple

Type[] types = Assembly.Load(new AssemblyName("mynamespace.folder")).GetTypes();
foreach (var item in types)
{
}

//a simple combined code snippet 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace MustHaveAttributes
{
  class Program
  {
    static void Main ( string[] args )
    {
      Console.WriteLine ( " START " );

      // what is in the assembly
      Assembly a = Assembly.Load ( "MustHaveAttributes" );
      Type[] types = a.GetTypes ();
      foreach (Type t in types)
      {

        Console.WriteLine ( "Type is {0}", t );
      }
      Console.WriteLine (
         "{0} types found", types.Length );

      #region Linq
      //#region Action


      //string @namespace = "MustHaveAttributes";

      //var q = from t in Assembly.GetExecutingAssembly ().GetTypes ()
      //        where t.IsClass && t.Namespace == @namespace
      //        select t;
      //q.ToList ().ForEach ( t => Console.WriteLine ( t.Name ) );


      //#endregion Action  
      #endregion

      Console.ReadLine ();
      Console.WriteLine ( " HIT A KEY TO EXIT " );
      Console.WriteLine ( " END " );
    }
  } //eof Program


  class ClassOne
  {

  } //eof class 

  class ClassTwo
  {

  } //eof class


  [System.AttributeUsage ( System.AttributeTargets.Class |
    System.AttributeTargets.Struct, AllowMultiple = true )]
  public class AttributeClass : System.Attribute
  {

    public string MustHaveDescription { get; set; }
    public string MusHaveVersion { get; set; }


    public AttributeClass ( string mustHaveDescription, string mustHaveVersion )
    {
      MustHaveDescription = mustHaveDescription;
      MusHaveVersion = mustHaveVersion;
    }

  } //eof class 

} //eof namespace 

Namespaces are actually rather passive in the design of the runtime and serve primarily as organizational tools. The Full Name of a type in .NET consists of the Namespace and Class/Enum/Etc. combined. If you only wish to go through a specific assembly, you would simply loop through the types returned by assembly.GetExportedTypes() checking the value of type.Namespace. If you were trying to go through all assemblies loaded in the current AppDomain it would involve using AppDomain.CurrentDomain.GetAssemblies()


Just like @aku answer, but using extension methods:

string @namespace = "...";

var types = Assembly.GetExecutingAssembly().GetTypes()
    .Where(t => t.IsClass && t.Namespace == @namespace)
    .ToList();

types.ForEach(t => Console.WriteLine(t.Name));

Get all classes by part of Namespace name in just one row:

var allClasses = Assembly.GetExecutingAssembly().GetTypes().Where(a => a.IsClass && a.Namespace != null && a.Namespace.Contains(@"..your namespace...")).ToList();

As FlySwat says, you can have the same namespace spanning in multiple assemblies (for eg System.Collections.Generic). You will have to load all those assemblies if they are not already loaded. So for a complete answer:

AppDomain.CurrentDomain.GetAssemblies()
                       .SelectMany(t => t.GetTypes())
                       .Where(t => t.IsClass && t.Namespace == @namespace)

This should work unless you want classes of other domains. To get a list of all domains, follow this link.


using System.Reflection;
using System.Collections.Generic;
//...

static List<string> GetClasses(string nameSpace)
{
    Assembly asm = Assembly.GetExecutingAssembly();

    List<string> namespacelist = new List<string>();
    List<string> classlist = new List<string>();

    foreach (Type type in asm.GetTypes())
    {
        if (type.Namespace == nameSpace)
            namespacelist.Add(type.Name);
    }

    foreach (string classname in namespacelist)
        classlist.Add(classname);

    return classlist;
}

NB: The above code illustrates what's going on. Were you to implement it, a simplified version can be used:

using System.Linq;
using System.Reflection;
using System.Collections.Generic;
//...

static IEnumerable<string> GetClasses(string nameSpace)
{
    Assembly asm = Assembly.GetExecutingAssembly();
    return asm.GetTypes()
        .Where(type => type.Namespace == nameSpace)
        .Select(type => type.Name);
}

Here's a fix for LoaderException errors you're likely to find if one of the types sublasses a type in another assembly:

// Setup event handler to resolve assemblies
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);

Assembly a = System.Reflection.Assembly.ReflectionOnlyLoadFrom(filename);
a.GetTypes();
// process types here

// method later in the class:
static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
    return System.Reflection.Assembly.ReflectionOnlyLoad(args.Name);
}

That should help with loading types defined in other assemblies.

Hope that helps!


You won't be able to get all types in a namespace, because a namespace can bridge multiple assemblies, but you can get all classes in an assembly and check to see if they belong to that namespace.

Assembly.GetTypes() works on the local assembly, or you can load an assembly first then call GetTypes() on it.


For a specific Assembly, NameSpace and ClassName:

var assemblyName = "Some.Assembly.Name"
var nameSpace = "Some.Namespace.Name";
var className = "ClassNameFilter";

var asm = Assembly.Load(assemblyName);
var classes = asm.GetTypes().Where(p =>
     p.Namespace == nameSpace &&
     p.Name.Contains(className) 
).ToList();

Note: The project must reference the assembly


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to reflection

Get properties of a class Get class name of object as string in Swift Set field value with reflection Using isKindOfClass with Swift I want to get the type of a variable at runtime Loading DLLs at runtime in C# How to have Java method return generic list of any type? Java reflection: how to get field value from an object, not knowing its class Dynamically Add C# Properties at Runtime Check if a property exists in a class

Examples related to namespaces

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model How do I get an object's unqualified (short) class name? socket.error:[errno 99] cannot assign requested address and namespace in python What is the use of "using namespace std"? Visibility of global variables in imported modules Using :: in C++ 'namespace' but is used like a 'type' type object 'datetime.datetime' has no attribute 'datetime' Why am I getting error CS0246: The type or namespace name could not be found? string in namespace std does not name a type