dimanche 9 février 2020

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?





Aucun commentaire:

Enregistrer un commentaire