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
Release: 2025-01-04 00:31:44
Original
325 people have browsed it

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();
}
Copy after login

Example usage:

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

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template