Home >Backend Development >C++ >How to Retrieve All Classes within a Specific Namespace in C#?

How to Retrieve All Classes within a Specific Namespace in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-04 00:31:44324browse

How to Retrieve All Classes within a Specific Namespace in C#?

Retrieving Classes within a Namespace in C#

In C#, obtaining all classes within a specific namespace requires an indirect approach. To accomplish this:

  1. Enumerate Assembly Types:

    • Retrieve all types within the assembly under scrutiny.
  2. Filter by Namespace:

    • Verify the namespace of each type, retaining only those within the target namespace.

The following code snippet demonstrates this process:

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

Example usage:

Assembly executingAssembly = Assembly.GetExecutingAssembly();
Type[] typelist = GetTypesInNamespace(executingAssembly, "MyNamespace");
for (int i = 0; i < typelist.Length; i++)
{
    Console.WriteLine(typelist[i].Name);
}

For .NET versions prior to 2.0, where Assembly.GetExecutingAssembly() is unavailable:

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

The above is the detailed content of How to Retrieve All Classes within a Specific Namespace in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn