tags:

views:

54

answers:

3

Assmbly.GetTpes() gets the types in the assembly but if I also wants nested class (OrderLine) how do I do that? I only know the name of the assembly, not the class names so GetType(Order+OrderLine) will not work.

public class Order
{
  public class OrderLine
  {
  }
}
A: 

You can use a LINQ statement. I'm not 100% sure what you're trying to do, but you can do something like this.

Assembly.GetTypes().Where(type => type.IsSubclassOf(SomeType) && type.Whatever);

Edit

If the normal Assembly.GetTypes() isn't returning your nested class, you could iterate over the array and add everything you find in CurrentType.GetNestedTypes() to the array. like

 var allTypes = new List<Type>();
 var types = Assembly.GetTypes();
 allTypes.AddRange(types);
 foreach(var type in types)
 {
     allTypes.AddRange(type.GetNestedTypes());
 }
Stefan Valianu
Nested classes aren't necessarily subclasses, and subclasses aren't necessarily nested. This doesn't do what the asker wants.
Greg
@Greg I was just demonstrating an example of a LINQ statement.
Stefan Valianu
+2  A: 

Something like this:


Assembly.GetTypes().SelectMany(t => new [] { t }.Concat(t.GetNestedTypes()));
STO
Ooh, SelectMany. *rushes off to MSDN to absorb info*
Stefan Valianu
+3  A: 

I don't know if assembly.GetTypes() is supposed to include nested classes. Assuming it doesn't, a method like the following could iterate over all the assembly's types.

IEnumerable<Type> AllTypes(Assembly assembly)
{
    foreach (Type type in assembly.GetTypes())
    {
        yield return type;        
        foreach (Type nestedType in type.GetNestedTypes())
        {
            yield return nestedType;
        }
    }
}

Edit:
MSDN has the following to say about Assembly.GetTypes

The returned array includes nested types.

So really my above answer shouldn't be necessary. You should find both Order and Order+OrderLine returned as types by Assembly.GetTypes.

Greg
This wouldn't pick up nested types within nested types. But really, who does that?
Stefan Valianu
@Stefan - Detecting nested-nested-nested types is an exercise in recursion left to the reader
Greg