silent_coder
silent_coder

Reputation: 6532

Can't create instance of generated type: No parameterless constructor defined for this object

I'm generating new dynamic type and wan't to create it's instance. But when actually create instantiation code, it's fails with exception: No parameterless constructor defined for this object.

My code is the following:

AssemblyBuilder aBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("dfsdfsdf"), AssemblyBuilderAccess.Run);
ModuleBuilder mBuilder = aBuilder.DefineDynamicModule("dsadsadasdasda");
TypeBuilder typeBlank = mBuilder.DefineType("dasvvvvvvvv", TypeAttributes.Class | TypeAttributes.Public);
ConstructorBuilder cb = typeBlank.DefineDefaultConstructor(MethodAttributes.Public);
Type t = cb.GetType();
var item = Activator.CreateInstance(t);  // <--- Error appear in this line.

What is wrong there?

Upvotes: 0

Views: 10497

Answers (1)

D Stanley
D Stanley

Reputation: 152644

You're trying to create an instance of ConstructorBuilder, not your generated class.

I think you want:

...
ConstructorBuilder cb = typeBlank.DefineDefaultConstructor(MethodAttributes.Public);
Type t = typeBlank.CreateType();
var item = Activator.CreateInstance(t);  

Note that a parameterless default constructor is created by default; you don't need to create one except in the following circumstances:

(From MSDN):

Because the default constructor is automatically defined, it is necessary to call this method only in the following situations:

  • You have defined another constructor and you also want a default constructor that simply calls the base class constructor.
  • You want to set the attributes on the default constructor to something other than PrivateScope, Public, HideBySig, SpecialName, and RTSpecialName.

Upvotes: 6

Related Questions