user1634494
user1634494

Reputation: 629

How to grab every class from specified namespace c#?

So I have read a few ver similar questions, but the answers to those are not actually giving me a result.

My code now is

List<Type> theList = Assembly.GetExecutingAssembly().GetTypes().ToList().Where(t => t.Namespace == "foo.test").ToList();

And this does not actually return anything, even though there are multiple classes inside this namespace. There are three static classes inside foo.test which are TestOne, TestTwo, and TestThree; but none are returned in the little one liner I got from another stack overflow thread.

How do I grab these three static classes only given the namespace foo.test? My program namespace is foo.program, so both our namespaces are somewhat close, and I also have a using foo.test in my program includes.

Upvotes: 0

Views: 167

Answers (2)

David L
David L

Reputation: 33833

You're probably running into both case sensitivity and incomplete namespace name issues. You might be better off using case insensitive search coupled with IndexOf() for your current culture.

List<Type> theList = Assembly.GetExecutingAssembly().GetTypes().Where(t => 
    culture.CompareInfo.IndexOf(t.Namespace, "foo.test", CompareOptions.IgnoreCase))
   .ToList();

Alternatively, if you are CERTAIN that your namespace is correct, you can perform just a case insensitive search for that namespace.

List<Type> theList = Assembly.GetExecutingAssembly().GetTypes()
    .Where(t => t.Namespace.Equals("foo.test", StringComparison.CurrentCultureIgnoreCase))
    .ToList();

Finally, it's worth noting that this will only load types from your executing assembly! If the types live in an external assembly, this code will NOT retrieve them! If you had previously referenced the class in your code, forcing it to be loaded into the app domain, you could iterate over all loaded assemblies to look for your types.

List<Type> theList = new List<Type>();
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
    theList.AddRange(
        a.GetTypes()
           .Where(t =>     
               t.Namespace.Equals("foo.test", StringComparison.CurrentCultureIgnoreCase))
           .ToList());
}

Upvotes: 1

SLaks
SLaks

Reputation: 887777

This would happen if those types are defined in a different assembly, or if foo.test should actually be capitalized.

Upvotes: 0

Related Questions