I would like a method to check if a type is an Auto Generated type by the C# compiler (e.g. Lambda Closures, Actions, Nested Methods, Anonymous Types, etc).
Currently have the following:
public bool IsCompilerGenerated(Type type)
{
return type.Name.StartsWith("<>", StringComparison.OrdinalIgnoreCase);
}
With accompanying test:
public class UnitTest1
{
class SomeInnerClass
{
}
[Fact]
public void Test()
{
// Arrange - Create Compiler Generated Nested Type
var test = "test";
void Act() => _testOutputHelper.WriteLine("Inside Action: " + test);
// Arrange - Prevent Compiler Optimizations
test = "";
Act();
var compilerGeneratedTypes = GetType().Assembly
.GetTypes()
.Where(x => x.Name.Contains("Display")) // Name of compiler generated class == "<>c__DisplayClass5_0"
.ToList();
Assert.False(IsCompilerGenerated(typeof(SomeInnerClass)));
Assert.NotEmpty(compilerGeneratedTypes);
Assert.All(compilerGeneratedTypes, type => Assert.True(IsCompilerGenerated(type)));
}
}
Is there any better way to check for compiler generated types rather than the name?
Assuming that Microsoft follows their own guidance for application of the System.Runtime.CompilerServices.CompilerGeneratedAttribute,
Remarks
Apply the CompilerGeneratedAttribute attribute to any application element to indicate that the element is generated by a compiler.
Use the CompilerGeneratedAttribute attribute to determine whether an element is added by a compiler or authored directly in source code.
you can check the type's CustomAttributes to determine if the type is so decorated with something like this:
using System.Reflection;
public bool IsCompilerGenerated(Type type)
{
return type.GetCustomAttribute<System.Runtime.CompilerServices.CompilerGeneratedAttribute>() != null;
}
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