I'm creating a type at runtime using Reflection.Emit. The problem is that whenever I instantiate an instance of the new type I have to use object or dynamic because the type isn't known at compile time. This works fine except for when I would want another type to implicitly cast to the new type during assignment. The variable happily takes on the new value and it's corresponding type without attempting to cast to its current type.
Is there any way to create a variable of a newly created type that will allow for implicit casting? I'm perfectly happy to give up compile-time checking but I would like these casts to at least be attempted at run-time.
Edit:
Here is an example to make it more clear. This is what happens when you know the type at compile-time:
MyClass a;
//this calls the implicit cast operator and 'a' stays of the same type
a = 5;
and this is what happens if you don't:
Type t = CreateTypeUsingTypeBuilder();
object a = Activator.CreateInstance(t);
//this does not call the implicit cast operator and 'a' just becomes in integer
a = 5;
Also, I'm not surprised at this behavior or asking why it happens. I'm asking if there is any sort of workaround to achieve the desired behavior of having it check for an implicit operator at run-time.
In order to understand why this is not possible, at least not directly, one needs to understand how implicit conversion operators work in the first place.
When you write something like this
the compiler realizes that
xandyare of different types, and searchesMyNumericTypeto see if there is an implicit conversion operator defined:Once the operator is found, the compiler invokes it as if it were a regular
staticmethod (which it is).When you work with types generated at runtime, you should generate the conversion at runtime as well. For example, if you do this
With this method in place you can do this: