15

I need to programmatically get a List of all the classes in a given namespace. How can I achieve this (reflection?) in C#?

1
  • How annoying when a question gets marked as a duplicate and the original is not referenced.
    – War
    Nov 9, 2014 at 15:06

4 Answers 4

39
var theList = Assembly.GetExecutingAssembly().GetTypes()
                      .Where(t => t.Namespace == "your.name.space")
                      .ToList();
4
  • There's always the "one-liners". ;-)
    – Wim
    Dec 2, 2009 at 20:56
  • 1
    Yeah, you gotta love a one-liner :-) Dec 2, 2009 at 21:02
  • 3
    This assumes the whole namespace is in the current assembly, A partial solution at best.
    – War
    Nov 9, 2014 at 15:03
  • 1
    War, what would be a better solution then? Feb 7, 2017 at 18:07
5

Without LINQ:

Try:

Type[] types = Assembly.GetExecutingAssembly().GetTypes();
List<Type> myTypes = new List<Type>();
foreach (Type t in types)
{
  if (t.Namespace=="My.Fancy.Namespace")
    myTypes.Add(t);
}
5
  • Assembly.GetExecutingAssembly().GetTypes().ToList() will give you the list you want.
    – Gregory
    Dec 2, 2009 at 20:51
  • Yes Greg, though technically, that is using a LINQ extension method and my example was meant to show this without having .NET 3.5
    – Wim
    Dec 2, 2009 at 20:55
  • clean non linq example though OP doesn't say that the assembly has already been loaded so the code might return an empty set eventhough the list should have been long and a name space might be in more assemblies :)
    – Rune FS
    Dec 2, 2009 at 21:06
  • Fair point, I should have just created a method with an Assembly parameter as input and left the client call up to the OP altogether. ;-)
    – Wim
    Dec 2, 2009 at 21:43
  • Same namespaces in more assemblies is not how I would design it. Fine for base namespaces, but I definitely wouldn't have types in the same namespaces spread out over multiple assemblies. That's nasty.
    – Wim
    Dec 2, 2009 at 21:45
2

Take a look at this How to get all classes within namespace? the answer provided returns an array of Type[] you can modify this easily to return List

1

I can only think of looping through types in an assebly to find ones iin the correct namespace

public List<Type> GetList()
        {
            List<Type> types = new List<Type>();
            var assembly = Assembly.GetExecutingAssembly();
            foreach (var type in assembly .GetTypes())
            {
                if (type.Namespace == "Namespace")
                {
                    types.Add(type);
                }
            }
            return types;
        }

Not the answer you're looking for? Browse other questions tagged or ask your own question.