This is a followup to this question which I tried and failed to explain in my answer.
DateTime implements IConvertible. You can prove this because
IConvertible dt = new DateTime();
compiles without an issue.
You can write the following code and there are no compile errors
IConvertible dt = new DateTime();
dt.ToDateTime(val);
However if you write the next code fragment it doesn't compile
DateTime dt = new DateTime();
dt.ToDateTime(val);
'System.DateTime' does not contain a definition for 'ToDateTime'
If DateTime implements the interface why can you not call the method on a DateTime unless it's cast to an IConvertible?
Because DateTime
implements IConvertible
interface explicitly - this method is listed in Explicit Interface Implementations section on MSDN. And here is how it implemented:
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return this;
}
You should cast DateTime
to IConvertible
:
DateTime dt = new DateTime();
var result = ((IConvertible)dt).ToDateTime(val);
See Explicit Interface Implementation (C# Programming Guide)
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