Chat LIVE With Programming Experts! There Are 23 Online Right Now...

 

Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Become a C# Expert!

Join 244,296 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 873 people online right now. Registration is fast and FREE... Join Now!





Find all classes within a Namespace

This little snippet will return a list populated with all the classes in the Namespace you provide it

Submitted By: PsychoCoder
Actions:
Rating:
Views: 13,833

Language: C#

Last Modified: December 20, 2007
Instructions: Pass the method the Namespace you want to search and it will return a list populated with all classes in that Namespace

Snippet


  1. //add these references to your class
  2. using System.Reflection;
  3. using System.Collections.Generic;
  4.  
  5.  
  6. /// <summary>
  7. /// Method to populate a list with all the class
  8. /// in the namespace provided by the user
  9. /// </summary>
  10. /// <param name="nameSpace">The namespace the user wants searched</param>
  11. /// <returns></returns>
  12. static List<string> GetAllClasses(string nameSpace)
  13. {
  14.     //create an Assembly and use its GetExecutingAssembly Method
  15.     //http://msdn2.microsoft.com/en-us/library/system.reflection.assembly.getexecutingassembly.aspx
  16.     Assembly asm = Assembly.GetExecutingAssembly();
  17.     //create a list for the namespaces
  18.     List<string> namespaceList = new List<string>();
  19.     //create a list that will hold all the classes
  20.     //the suplied namespace is executing
  21.     List<string> returnList = new List<string>();
  22.     //loop through all the "Types" in the Assembly using
  23.     //the GetType method:
  24.     //http://msdn2.microsoft.com/en-us/library/system.reflection.assembly.gettypes.aspx
  25.     foreach (Type type in asm.GetTypes())
  26.     {
  27.         if (type.Namespace == nameSpace)
  28.             namespaceList.Add(type.Name);
  29.     }
  30.     //now loop through all the classes returned above and add
  31.     //them to our classesName list
  32.     foreach (String className in namespaceList)
  33.         returnList.Add(className);
  34.     //return the list
  35.     return returnList;
  36. }

Copy & Paste


Comments


Public_account 2008-02-22 18:35:09

cool idea, however I don't see the point of the two lists. You are creating namespaceList, then iterating it to create returnList. You can eliminate the second loop and just return namespaceList.

mds 2009-03-25 16:17:44

It doesn't work very well :(


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C# Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month