Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly.GetTypes() for nested classes

Tags:

c#

reflection

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
  {
  }
}
like image 900
Martin Nilsson Avatar asked Jun 21 '10 18:06

Martin Nilsson


2 Answers

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.

like image 66
Greg Avatar answered Nov 05 '22 05:11

Greg


Something like this:


Assembly.GetTypes().SelectMany(t => new [] { t }.Concat(t.GetNestedTypes()));
like image 5
STO Avatar answered Nov 05 '22 03:11

STO