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?
This depends on the exact use case, a possible solution is to make your class generic, then use reflection to create a static generic method that creates an instance of the class. This allows you to use the variable dynamic type when declaring your property:
Another alternative is using the dynamic keyword.