Liath
Liath

Reputation: 10191

Why does DateTime.ToDateTime( ) not compile?

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?

Upvotes: 4

Views: 650

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

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)

Upvotes: 11

Related Questions