Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get all classes within a namespace?

People also ask

How many classes can a single namespace contains?

Two classes with the same name can be created inside 2 different namespaces in a single program. Inside a namespace, no two classes can have the same name.

Can we declare class inside namespace?

A class can also be declared inside namespace and defined outside namespace using the following syntax: CPP.

Are namespaces the same as classes?

Classes are data types. They are an expanded concept of structures, they can contain data members, but they can also contain functions as members whereas a namespace is simply an abstract way of grouping items together. A namespace cannot be created as an object; think of it more as a naming convention.


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

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)