I need a reliable way to distinguish compiler generated closure objects.
I found a viable solution using CompilerGeneratedAttribute: How to distingush compiler-generated classes from user classes in .NET It turns out i can use CompilerGeneratedAttribute.
Here is my current code:
static bool IsClosure(Type t)
{
return IsCompilerGenerated(t) && !t.Name.Contains("AnonymousType");
}
static bool IsCompilerGenerated(Type t)
{
return Attribute.IsDefined(t, typeof(CompilerGeneratedAttribute), false);
}
void Main()
{
var site = new Model();
var propertyExpression = (Expression<Func<string>>)(() => site.Prop);
var memberAccess = (MemberExpression)propertyExpression.Body;
var modelExpression = (MemberExpression)memberAccess.Expression;
var closureExpression = (ConstantExpression)modelExpression.Expression;
var closureType = closureExpression.Value.GetType();
Console.WriteLine("Type: {0} Is closure: {1}", closureType, IsClosure(closureType));
var anonymous = new { x = 0 };
Console.WriteLine("Type: {0} Is closure: {1}", anonymous.GetType(), IsClosure(anonymous.GetType()));
}
class Model
{
public string Prop { get; set; }
}
Output:
Type: MyClass+<>c__DisplayClass0_0 Is closure: True
Type: <>f__AnonymousType0`1[System.Int32] Is closure: False
As i understand from and Anonymous Types - Are there any distingushing characteristics? about anonymous objects, is that the problem is similar for compiler generated closure types, and distinguishing characteristics are essentially an implementation detail. Is that the case?
Is there a more reliable method to distinguish closure objects, considering portability to mono and future versions of .NET?