Home >Backend Development >C++ >How to Get All Classes from a Namespace in C#?
How to Retrieve All Classes Within a Namespace in C#
Enumerating all classes within a specified namespace is achievable in C# through a technique that examines all types within an assembly and filters them based on their namespaces. Here's the approach in detail:
using System.Reflection; private Type[] GetTypesInNamespace(Assembly assembly, string nameSpace) { return assembly.GetTypes() .Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)) .ToArray(); }
Sample Usage:
Type[] typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyNamespace"); for (int i = 0; i < typelist.Length; i++) { Console.WriteLine(typelist[i].Name); }
Prior to .Net 2.0, where Assembly.GetExecutingAssembly() is unavailable, an alternative approach involving typeof() is required to obtain 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); }
By utilizing these techniques, developers can effectively retrieve all classes residing within a specific namespace, enabling dynamic class enumeration in C# applications.
The above is the detailed content of How to Get All Classes from a Namespace in C#?. For more information, please follow other related articles on the PHP Chinese website!