Given this class with an implicit cast operator:
public class MyDateTime
{
public static implicit operator MyDateTime(System.Int64 encoded)
{
return new MyDateTime(encoded);
}
public MyDateTime(System.Int64 encoded)
{
_encoded = encoded;
}
System.Int64 _encoded;
}
I can now do the following:
long a = 5;
MyDateTime b = a;
But NOT the following:
long f = 5;
object g = f;
MyDateTime h = g;
This gives a compile time:
Cannot implicitly convert type 'object' to 'MyDateTime'.
Makes sense to me.
Now I modify the previous example as follows:
long f = 5;
object g = f;
MyDateTime h = (MyDateTime)g;
This compiles fine. Now I get a runtime InvalidCastException
:
Unable to cast object of type 'System.Int64' to type MyDateTime'.
This tells me that C# implicit cast operators are applied at compile time only, and are not applied when the .NET runtime is attempting to dynamically cast an object to another type.
My questions:
- Am I correct?
- Is there some other way to do this?
By the way, the full application is that I'm using Delegate.DynamicInvoke()
to call a function that takes a MyDateTime
parameter, and the type of the argument I'm passing to DynamicInvoke
is a long.