4

To put it simple, I want all the namespaces in the project recursively, and classes available in all namespaces found earlier.

var namespaces = assembly.GetTypes() .Select(ns => ns.Namespace); 

I am using this part earlier to get the namespaces in string format. But now i got to know the underlying namespaces as well.

1 Answer 1

4

It sounds like you might want a Lookup from namespace to class:

var lookup = assembly.GetTypes().ToLookup(t => t.Namespace); 

Or alternatively (and very similarly) you could use GroupBy:

var groups = assembly.GetTypes().GroupBy(t => t.Namespace); 

For example:

var groups = assembly.GetTypes() .Where(t => t.IsClass) // Only include classes .GroupBy(t => t.Namespace); foreach (var group in groups) { Console.WriteLine("Namespace: {0}", group.Key); foreach (var type in group) { Console.WriteLine(" {0}", t.Name); } } 

However, it's not entirely clear whether that's what you're after. That will get you the classes in each namespace, but I don't know whether that's really what you're looking for.

Two points to bear in mind:

  • There's nothing recursive about this
  • Namespaces don't really form a hierarchy, as far as the CLR is concerned. There's no such thing as an "underlying" namespace. The C# language itself does have some rules about this, but as far as the CLR is concerned, there's no such thing as a "parent" namespace.

If you really want to go from "Foo.Bar.Baz" to "Foo.Bar" and "Foo" then you can use something like:

while (true) { Console.WriteLine(ns); int index = ns.LastIndexOf('.'); if (index == -1) { break; } ns = ns.Substring(0, index); } 
Sign up to request clarification or add additional context in comments.

11 Comments

@Jon Skeet: Thank you so much. Especially your knowledge on .Net is great. I would like to be a student of yours. :)
@Jon Skeet: I also want to know more about Reflection. I underestimated Reflection earlier. So I want to know more about this. Is there any way i can get most of the experimental knowledge on this topic. I know one method, trying. :) If there is any source, please suggest me.
@Prakash: Trying is a really good option when it comes to reflection, to be honest. Have a look at all the members of things like Type and MethodInfo, and think of places where they could be useful.
@Jon Skeet: The code you gave should be updated to give out only classes. right now it gives all the types in the namespace including interfaces, enum, structure. And how to filter abstract classes from the class..?
@Prakash: Just use a "Where" call in the LINQ query e.g. using Type.IsClass. I'll edit the answer for that one; for other conditions you'd just adjust that condition.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.