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.
Asked
Active
Viewed 5,239 times
11

Linger
- 14,942
- 23
- 52
- 79

Sebastian Müller
- 5,471
- 13
- 51
- 79
-
Possible duplicate of [Getting all types in a namespace via reflection](https://stackoverflow.com/questions/79693/getting-all-types-in-a-namespace-via-reflection) – puzzlepiece87 Sep 13 '19 at 21:20
1 Answers
23
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);
}

MPelletier
- 16,256
- 15
- 86
- 137

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194