Search code examples
c#.netreflectiontypesreflection.emit

TypeAttribute for static classes


I am trying to define a new type via Reflection.Emit, but I can't manage to find a TypeAttribute that will define the type as static.

For instance, let's say I want to create the following type:

public static class Hello
{
}

I can identify the following attributes:

TypeAttributes.Class
TypeAttributes.Public

But how's that different from

public class Hello
{
}

I was thinking maybe to add TypeAttributes.Abstract (because one cannot instantiate it), but I wasn't sure about that, since abstract classes are totally different.


Solution

  • You can use reflection to view what the c# compiler will generate in each case.

    public class Program
    {
        public static void Main()
        {
            Console.WriteLine(typeof(StaticClass).Attributes);
            Console.WriteLine(typeof(NotStaticClass).Attributes);
        }
    }
    
    public static class StaticClass { }
    
    public class NotStaticClass { }
    

    will produce:

    AutoLayout, AnsiClass, Class, Public, Abstract, Sealed, BeforeFieldInit

    AutoLayout, AnsiClass, Class, Public, BeforeFieldInit