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:
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.
An implicit dynamic conversion exists from an expression of type dynamic to any type T .
Implicit Type Conversion In C Notice that we have assigned the double value to an integer variable. int number = value; Here, the C compiler automatically converts the double value 4150.12 to integer value 4150. Since the conversion is happening automatically, this type of conversion is called implicit type conversion.
The usual arithmetic conversions are performed implicitly for the following operators: Arithmetic operators with two operands: * , / , % , + , and - Relational and equality operators: < , <= , > , >= , == , and != The bitwise operators, & , | , and ^
Implicit Conversions There is no special syntax for this type of conversion, this is the safest type of casting. No data is lost, for example, when converting from smaller to larger integral types or derived classes to base classes.
Am I correct?
Yes, yes you are. To be nit-picky, you should be saying "user-defined implicit conversion" rather than "implicit cast" -- a cast is (almost) always explicit. But your deduction that overload resolution chooses which user-defined conversion to call at compile time and not at run time is correct.
Is there some other way to do this?
Yes. In C# 4 if you type your "object" as "dynamic" then we start up the compiler again at runtime and re-perform all the analysis on the operands as though their compile-time types were the current run-time types. As you might imagine, this is not cheap, though we are very smart about caching and re-using the results should you do this in a tight loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With