0

I need a way to check out all namespaces used by a type via reflection.

namespace My.Program.BaseTypes { using System; using System.Text; using My.Program.Extenders; using My.Program.Helpers; using My.Program.Interfaces; public class MyTypeBase { public MyTypeBase() { } public My.Program.Helpers.HelperTypeX X { get; set; } public My.Program.Extenders.ExtenderTypeY Y { get; set; } public My.Program.Interfaces.InterfaceZ IZ { get; set; } } } 

I have only the Type of MyTypeBase in my code and need to find out with reflection all referenced namespaces of all Properties in MyTypeBase.

Sure I could loop through all Properties, get the types from them and check their namespaces, but is there a cleaner way of achiving this goal?

To prevent the question, it is for writing a generator which shall create new classes based on some legacy code.

1 Answer 1

1

No, I can't think of a cleaner way of doing this. There's no real concept of the type itself using a bunch of namespaces - it has members which themselves refer to types (either in property/return type, field type, event handler type, the type of a nested class, or a parameter type) but those are just individual members.

On the plus side, with LINQ it shouldn't be hard to do... something like:

var namespaces = type.GetProperties() .Select(p => p.PropertyType.Namespace) .Distinct(); 

Note that that won't pick up the namespaces of indexer parameter types.

Sign up to request clarification or add additional context in comments.

1 Comment

I thought of something like this, need to read your book faster to get in touch with linq and lambda expressions ;-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.