In the code below:
void Main()
{
DateTime cleanDate = DateTime.Now.ToCleanDateTime();
DateTime? nullableCleanDate = DateTime.Now;
nullableCleanDate = nullableCleanDate.ToCleanDateTime();
cleanDate.Dump();
nullableCleanDate.Dump();
}
public static class Extensions
{
//public static DateTime ToCleanDateTime(this DateTime dt)
//{
// dt = new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0, 0);
// return dt;
//}
public static DateTime? ToCleanDateTime(this DateTime? dt)
{
if (dt.HasValue)
dt = new DateTime(dt.Value.Year, dt.Value.Month, dt.Value.Day, 0, 0, 0, 0);
return dt;
}
}
This line DateTime cleanDate = DateTime.Now.ToCleanDateTime();
throws following exception.
'System.DateTime' does not contain a definition for 'ToCleanDateTime' and the best extension method overload 'Extensions.ToCleanDateTime(System.DateTime?)' has some invalid arguments
If I comment in extension method for DateTime
public static DateTime ToCleanDateTime(this DateTime dt)
error is not thrown.
Could anyone enlighten me with:
- Why is this error thrown (aside from the obvious)?
- Is there a way to combine these two extensions into single method?
I somehow expected public static DateTime? ToCleanDateTime(this DateTime? dt)
to handle both DateTime
and DateTime?
.
DateTime
!=DateTime?
becauseDateTime?
is turned intoNullable<DateTime>
by the compiler. Its a completely different type. – Elman