How to Get All Classes Within a Namespace

How can I get all classes within a namespace?

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

Get all classes inside a namespace

As @hawk mentioned, the answer is located here, with sample code that you can use:

Getting all types in a namespace via reflection

Create a list of all classes in namespace using reflection and cast to their real type

SOLVED: The issue was I had internal constructors and the System.Activator couldn't create an instance of the class.

Get list of classes in namespace in C#

var theList = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.Namespace == "your.name.space")
.ToList();

call method from all classes within namespace

First: please show us what you have accomplished till now

Second:You might consider to call the method by it's string name

Check the following answer on stackoverflow :

https://stackoverflow.com/a/540075/7120278

If you use the example i mentioned you can create any set of objects and call the method

Loop through all classes in a given namespace and create an object for each?

Try Assembly.GetTypes(). Then filter them by the namespace (and ensure they are what you want). To instantiate them, use Activator.CreateInstance(...).

C# Get a List of Classes in a Namespace per Reflection

because adding Type to combobox makes type.ToString() and puts string representation into combobox, you can use

var instance = Activator.CreateInstance(Type.GetType(cbModule4.SelectedText))

When passing type, you can do:

var instance = Activator.CreateInstance(theList[0]))



Related Topics



Leave a reply



Submit