Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 118,923 C# Programmers for FREE! Ask your question and get quick answers from experts. There are 1,971 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! 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: 5,994

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.


Add comment


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





Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month