I have a piece of code in my program that distinguishes compiler-generated classes by checking whether they contain "DisplayClass" in its type name.
upon reading this answer, I think I need a better way. How to distingush compiler-generated classes from user classes in .NET?
Asked
Active
Viewed 5,926 times
7
2 Answers
15
Check classes for attribute CompilerGenerated
to distinguish compiler generated classes from other
In reflector those Display classes can be seen like this:
[CompilerGenerated]
private sealed class <>c__DisplayClass1
{..}

Valentin Kuzub
- 11,703
- 7
- 56
- 93
-
1Note: if you autogenerate code yourself, use the `GenerateCodeAttribute`, instead of the `CompilerGeneratedAttribute`, as [explained by David Kean in this MSDN blog](http://blogs.msdn.com/b/codeanalysis/archive/2007/04/27/correct-usage-of-the-compilergeneratedattribute-and-the-generatedcodeattribute.aspx). – Abel Nov 26 '15 at 00:52
-
The article is no longer available but thanks for the hint – thomasgalliker Feb 08 '23 at 05:46
7
This answer really helped me out! Here's the code I needed to add to check a Type
for the CompilerGeneratedAttribute
as Valentin Kuzub mentioned:
using System.Runtime.CompilerServices;
//...
bool IsCompilerGenerated(Type t)
{
var attr = Attribute.GetCustomAttribute(t, typeof(CompilerGeneratedAttribute));
return attr != null;
}

cod3monk3y
- 9,508
- 6
- 39
- 54