Reputation: 81771
When creating a dynamic type in .NET, a default constructor is generated. How do I suppress that?
var typeBuilder = moduleBuilder.DefineType(
type.FullName,
TypeAttributes.NotPublic | TypeAttributes.BeforeFieldInit);
Upvotes: 1
Views: 298
Reputation: 11791
This is documented in the "Remarks Section" of the TypeBuilder.DefineConstructor Method.
If you do not define a constructor for your dynamic type, a default constructor is provided automatically, and it calls the default constructor of the base class.
If you define a constructor for your dynamic type, a default constructor is not provided. You have the following options for providing a default constructor in addition to the constructor you defined:
If you want a default constructor that simply calls the default constructor of the base class, you can use the DefineDefaultConstructor method to create one (and optionally restrict access to it). Do not provide an implementation for this default constructor. If you do, an exception is thrown when you try to use the constructor. No exception is thrown when the CreateType method is called.
If you want a default constructor that does something more than simply calling the default constructor of the base class, or that calls another constructor of the base class, or that does something else entirely, you must use the TypeBuilder.DefineConstructor method to create one, and provide your own implementation.
This behavior is no different than if you define a class without explicitly defining a default constructor; the compiler generates a public default constructor that calls the base constructor.
If you want a private default constructor, then:
ConstructorBuilder ctor = typeBuilder.DefineDefaultConstructor(MethodAttributes.Private);
Edit:
In the comments, it was mentioned that a static
class does not have a constructor. After a bit of back and forth with Reflector, I determined that the following will create a static dynamic class with same default attributes generated by c#.
public void Test()
{
AssemblyName asmName = new AssemblyName("TestAsmStatic");
AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder mb = ab.DefineDynamicModule(asmName.Name, asmName.Name + ".dll");
TypeBuilder tb = mb.DefineType("StaticType", TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit | TypeAttributes.Abstract);
Type t = tb.CreateType();
ab.Save(asmName.Name + ".dll");
ConstructorInfo[] ci = t.GetConstructors((System.Reflection.BindingFlags)(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static));
Console.WriteLine(ci.Length.ToString());
}
Upvotes: 1