2

I have little question. I found this on internet:

Type t = typeof(MyClass);
MethodInfo[] mi = t.GetMethods();

Is there any way how to do same thing with namespaces? Or is there any another way to get all classes with names and System.Type instances? Long time ago I found something about listing the library. Please anybody help me.

user35443
  • 6,309
  • 12
  • 52
  • 75
  • 2
    You can get all classes from the system assembly using this little hack: `typeof(string).Assembly.GetTypes()`. – Sergey Kalinichenko Mar 27 '12 at 15:37
  • Ok. But what should I do if I need to get it from for example System.IO ? – user35443 Mar 27 '12 at 15:38
  • possible duplicate of [Finding all Namespaces in an assembly using Reflection (DotNET)](http://stackoverflow.com/questions/1549198/finding-all-namespaces-in-an-assembly-using-reflection-dotnet) – Bernard Mar 27 '12 at 15:38
  • And pls write it as answer. I'll mark it. – user35443 Mar 27 '12 at 15:38
  • @dasblinkenlight that would get everything in the mscorlib assembly, not System. – vcsjones Mar 27 '12 at 15:39
  • Each type has a `Namespace` property, you can filter on it using LINQ or a `foreach` loop, whatever you prefer. – Sergey Kalinichenko Mar 27 '12 at 15:39
  • 1
    Oh, the `System.IO` stuff will be there too: `mscorlib` has 2500+ classes. – Sergey Kalinichenko Mar 27 '12 at 15:48
  • Remember that there is no one-to-one (or one-to-many) relation between assemblies and namespaces. An assembly may contain many namespaces (not a big surprise) but a namespace may also be defined in multiple assemblies. Essentially the relationship is many-to-many. Asking for all the types in a particular namespace is not well defined unless you mention which assemblies to search. – Martin Liversage Mar 27 '12 at 15:56
  • Yes, I now it. But I made a mistake 'cause sometimes when I'm using sockets I must add System.Net into references in Viusal Studio... – user35443 Mar 27 '12 at 16:04

2 Answers2

2

If you want to get all of the classes in a particular namespace, you could do something like this:

var types = from type
            in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
            where type.Namespace == "System"
            select type;

This will look in all loaded assemblies for any type in the namespace System. You could of course change "System" to anything else you'd like, such as "System.IO".

vcsjones
  • 138,677
  • 31
  • 291
  • 286
2

You can get all classes from the mscorlib assembly using this little hack: typeof(string).Assembly.GetTypes(). You can further filter on it by FullName or Namespace property.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523