Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does DateTime.ToDateTime( ) not compile?

Tags:

c#

.net

interface

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?

like image 617
Liath Avatar asked Dec 20 '22 19:12

Liath


1 Answers

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)

like image 63
Sergey Berezovskiy Avatar answered Jan 03 '23 02:01

Sergey Berezovskiy