I'm using Reflection.Emit
and TypeBuilder
to create a new type at runtime. My setup is something like:
public class MyClass {
public object MyField = CreateInstanceOfNewType();
public MyClass() {}
}
The issue is that MyClass.MyField
is declared with type object
and so the implicit cast operators that exist for the new type are not called when castable types are assigned to MyClass.MyField
. Is there a way to set the type of the field to the newly created type so that it behaves similarly to how it would in the typical case?
If I've understood correctly, you want to initialize an object of your new type with an object of some castable type you've built an implicit cast operator for. I would suggest that instead of implicit operators you consider using constructors: use
Reflection.Emit
to create constructors that take one parameter of your castable types and use that parameter value to initialize the object of the new type. You want to have same result as this piece of code would do:You can then use
Activator.CreateInstance(Type type, params object[] arguments)
to make use of that constructor. Here's an example: