Question

I was going through Getting Started (with PostSharp)

And when I saw PostSharp injected (is this expression is right?) an aspect code into assembly,
I saw this oddly named class marked with CompilerGeneratedAttribute. alt text

It is named <>AspectsImplementationDetails_1.
As far as I know, class name cannot be started with <>.
But how is it possible for PostSharp to create such class?

Is <> some kind of unknown/internal operator?


[UPDATE] I did some testing and it looks like I was able to generate types with interesting names. alt text

Here is the sample code used

using System;
using System.Reflection;
using System.Reflection.Emit;

namespace ReflectionDemo
{
    class Program
    {
        public static void Main(string[] args)
        {
            var typeNames = new[] 
            {
                "<>", "-", "+", "~", "!", "@", "#", "$", "%", "^", "&", 
                "*", "(", ")", "="
            };
            const string assemblyName = "Test";
            foreach (var typeName in typeNames)
            {
                PrintTypeName(
                    BuildType(assemblyName, typeName).CreateType());
            }
        }

        private static void PrintTypeName(Type type)
        {
            Console.WriteLine("TypeName = '{0}'", type.FullName);
        }

        private static TypeBuilder BuildType(
            string assemblyName, string typeName)
        {
            var name = new AssemblyName(assemblyName);
            var assemblyBuilder = 
                AppDomain.CurrentDomain.DefineDynamicAssembly(
                    name, AssemblyBuilderAccess.Run);
            var moduleBuilder = 
                assemblyBuilder.DefineDynamicModule(name.Name, false);
            return moduleBuilder.DefineType(
                typeName, TypeAttributes.Public);
        }
    }
}
Was it helpful?

Solution

C# source code can't contain names starting with <>. But CLR names have more freedom, so compilers (like the C# compiler and PostSharp) can generate such names. This is very useful because it ensures that the compiler-generated names will never clash with the names you use in your source code. You'll also see them generated by the C# compiler itself, e.g. for anonymous types or for the backing fields of auto properties.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top