Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all types under a userdefined assembly

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.

like image 769
Sriram Avatar asked Mar 28 '17 11:03

Sriram


2 Answers

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));
like image 95
Jon Skeet Avatar answered Nov 11 '22 10:11

Jon Skeet


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());
like image 4
Yeldar Kurmangaliyev Avatar answered Nov 11 '22 11:11

Yeldar Kurmangaliyev