tags:

views:

183

answers:

3

Hi, I have a function that receive a type and returns true or false. I need to find out what are all types in a certain namespace that that function will return true for them. Thanks.

+10  A: 

Here's a function that gets all the classes in a namespace:

using System.Reflection;
using System.Collections.Generic;

/// <summary>
/// Method to populate a list with all the class
/// in the namespace provided by the user
/// </summary>
/// <param name="nameSpace">The namespace the user wants searched</param>
/// <returns></returns>
static List<string> GetAllClasses(string nameSpace)
{
    //create an Assembly and use its GetExecutingAssembly Method
    //http://msdn2.microsoft.com/en-us/library/system.reflection.assembly.getexecutingassembly.aspx
    Assembly asm = Assembly.GetExecutingAssembly();
    //create a list for the namespaces
    List<string> namespaceList = new List<string>();
    //create a list that will hold all the classes
    //the suplied namespace is executing
    List<string> returnList = new List<string>();
    //loop through all the "Types" in the Assembly using
    //the GetType method:
    //http://msdn2.microsoft.com/en-us/library/system.reflection.assembly.gettypes.aspx
    foreach (Type type in asm.GetTypes())
    {
        if (type.Namespace == nameSpace)
            namespaceList.Add(type.Name);
    }

    foreach (String className in namespaceList)
        returnList.Add(className);

    return returnList;
}

[Update]

Here's a more compact way to do it, but this requires .Net 3.5 (from here):

public static IEnumerable<Type> GetTypesFromNamespace(Assembly assembly, 
                                               String desiredNamepace)
{
    return assembly.GetTypes()
                   .Where(type => type.Namespace == desiredNamespace);
}
Andreas Grech
+1  A: 

System.Reflection.Assembly.GetTypes() : Gets all types defined in this assembly.*

Should do the job =)

Clement Herreman
+1  A: 

Add all the assemblies you want to search and implement the MyFunction method:

class Program
{
    static void Main(string[] args)
    {
        List<Assembly> assembliesToSearch = new List<Assembly>();
        // Add the assemblies that you want to search here:
        assembliesToSearch.Add(Assembly.Load("mscorlib")); // sample assembly, you might need Assembly.GetExecutingAssembly

        foreach (Assembly assembly in assembliesToSearch)
        {
            var typesForThatTheFunctionReturnedTrue = assembly.GetTypes().Where(type => MyFunction(type) == true);

            foreach (Type type in typesForThatTheFunctionReturnedTrue)
            {
                Console.WriteLine(type.Name);
            }
        }
    }

    static bool MyFunction(Type t)
    {
        // Put your logic here
        return true;
    }
}