I am creating a generic converter
Here is a sample code of the generic converter
bool TryReaderParse<TType>(object data, out TType value)
{
value = default(TType);
Type returnType = typeof(TType);
object tmpValue = null;
if (returnType == typeof(DateTime))
{
tmpValue = StringToDatetime(data.ToString());
}
else if (returnType == typeof(DateTime?)) // THIS IF FIRES
{
tmpValue = StringToNullableDatetime(data.ToString());
}
value = (TType)Convert.ChangeType(tmpValue, returnType); // THROWS
}
public DateTime? StringToNullableDatetime(string date)
{
DateTime? datetime = null;
if (!string.IsNullOrEmpty(date))
{
datetime = DateTime.Parse(date, new CultureInfo(Resources.CurrentCulture));
}
return datetime;
}
And this is how I use it:
void foo()
{
DateTime? date = null;
TryReaderParse<DateTime?>("25/12/2012", out date);
}
The thrown exception says that it cannot convert from DateTime
to Nullable<DateTime>
. Since, the method creates and returns a nullable type, how come the casting fails?
At the end, I want to have a nullable DateTime, in this particular example.
edit The problem is that StringToNullableDatetime
method returns a Datetime?
and the casting says that cannot convert from Datetime
Since the StringToNullableDatetime
method returns a nullable datetime, how is it possible that the Convert.ChangeType
cannot see that the passed argument is nullable?
Ps. I've read answers like this one that do the opposite (casting from nullable).
Convert.ChangeType
line cannot see that the passed argument is nullable – Dobruja