Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Class is Compiler Generated

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?

like image 436
Michal Ciechan Avatar asked Sep 06 '25 06:09

Michal Ciechan


1 Answers

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;
}
like image 62
TnTinMn Avatar answered Sep 07 '25 19:09

TnTinMn