Reputation: 1354
There is a class:
public class Date
{
private DateTime _dateTime;
public Date(DateTime dateTime)
{
_dateTime = dateTime;
}
public static implicit operator DateTime(Date d)
{
if (d == null)
return default(DateTime);
return d._dateTime;
}
public static implicit operator Date(DateTime dt)
{
return new Date(dt);
}
}
So, this code works fine:
Date d = DateTime.Now;
DateTime dt=new Date(DateTime.Now);
But this code doesn't work and throws InvalidCastException "Specified cast is not valid.":
Date d = DateTime.Now;
var obj = (Object)d;
DateTime dt = (DateTime)obj;
For me, this is expected behavior, but is there any hack to make this particular code work? (Without cast obj to Date)
Upvotes: 7
Views: 3334
Reputation: 2279
Conversion operators are resolved based on static types (compile-time), since they are not virtual
/abstract
.
You can use dynamic
(with all implications of using dynamic
) to opt in to run-time reflection based look up.
Date d = DateTime.Now;
var obj = (Object)d;
DateTime dt = (DateTime)(dynamic)obj;
Upvotes: 0
Reputation: 203811
User defined implicit/explicit conversion operators are an entirely compile time construct. The compiler is going to say something alone the lines of, "Hey, this person is trying to stick a Foo somewhere that expects a Bar. Is a Foo a Bar? No, it's not. Hmm...Oh, I see that Foo has defined an implicit conversion to Bar, I'll go stick in a call to that static conversion method, so that at runtime all of the types match up."
The runtime has no knowledge about implicit/explicit conversions. By the time the program has finished being compiled, those are just regular static methods, like any other static method. Since the compiler only sees conversions from Date
to object
and from object
to Date
, it never sees a place where it needs to add the implicit conversion calls. By the time the runtime gets to it, it only sees that the Date
isn't a DateTime
.
Upvotes: 9