6

I am trying to get all the types defined under a particular userdefined namespace

Assembly.GetEntryAssembly().GetTypes().Where(t => t.Namespace == "namespace")


    <>c__DisplayClass3_0    
    <>c__DisplayClass4_0    
    <>c__DisplayClass6_0    
    <>c__DisplayClass2_0    
    <>c__DisplayClass2_1    
    <>c__DisplayClass2_2    
    <>c__DisplayClass2_3    
    <>c__DisplayClass2_4    
    <>c__DisplayClass2_5    
    <>c__DisplayClass2_6    
    <>c__DisplayClass2_7    
    <>c__DisplayClass2_8

My question Why am i getting these extra type which are not defined under that namespace?

how do i select type that are user defined types?

some one explain me what are these and how they get defined under a userdefined namespace.

Sriram
  • 739
  • 7
  • 18

2 Answers2

8

Those are all types generated by the compiler. The C# compiler generates types to implement things like:

  • Lambda expressions and anonymous methods
  • Iterator blocks
  • Async methods
  • Anonymous types

All of them should have the CompilerGeneratedAttribute applied to them, so you can filter them out that way if you want:

var types = Assembly.GetEntryAssembly()
    .GetTypes()
    .Where(t => t.Namespace == "namespace")
    .Where(t => !t.GetTypeInfo().IsDefined(typeof(CompilerGeneratedAttribute), true));
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

These are generated by compiler for closures.

This question explains why they are created: Why does C# compiler create private DisplayClass when using LINQ method Any() and how can I avoid it?

You can check for CompilerGeneratedAttribute to know which classes are compiler-generated and remove them from your collection:

Assembly.GetEntryAssembly().GetTypes()
   .Where(t => t.Namespace == "namespace")
   .Where(x => !x.GetTypeInfo().GetCustomAttributes<CompilerGeneratedAttribute>().Any());
Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101