Sebastian Müller
Sebastian Müller

Reputation: 5589

Taking out all classes of a specific namespace

Is there a way to get an object from a specific namespace? Perhaps with the System.Reflections? I want to get all objects from type ITestType in the namespace Test.TestTypes as Objects so that I have a list of instances of TestType1, TestType2, TestType3 and so on. Can Someone help me? I don't know where to search for that.

Upvotes: 11

Views: 5405

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502176

You can find all the types within an assembly, and find all of those types which match the given namespace (this is really easy with LINQ) - but if you don't have a specific assembly to look through, you need to examine all of the possible ones.

However, if you're looking for a way of finding all the live objects, that's a different matter - and you can't do it without using the profiler API, as far as I'm aware. (Even then it may be hard - I don't know.)

Here's the LINQ query though:

public static IEnumerable<Type> GetTypesFromNamespace(Assembly assembly, 
                                               String desiredNamespace)
{
    return assembly.GetTypes()
                   .Where(type => type.Namespace == desiredNamespace);
}

Upvotes: 23

Related Questions