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.
Those are all types generated by the compiler. The C# compiler generates types to implement things like:
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));
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With