Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distingush compiler-generated classes from user classes in .NET

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?

like image 739
Yeonho Avatar asked Jun 20 '11 23:06

Yeonho


Video Answer


2 Answers

Check classes for attribute CompilerGenerated to distinguish compiler generated classes from other

http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.compilergeneratedattribute.aspx

In reflector those Display classes can be seen like this:

[CompilerGenerated]
private sealed class <>c__DisplayClass1
{..}
like image 153
Valentin Kuzub Avatar answered Sep 19 '22 16:09

Valentin Kuzub


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;
}
like image 28
cod3monk3y Avatar answered Sep 19 '22 16:09

cod3monk3y