i get data from xml file and sometime the date is empty.
i have this code:
try { TimeTo = Convert.ToDateTime(R[15].ToString()); }
catch { TimeTo = null ; }
but i got error because i cant insert null to datetime var
what i can do ?
thak's in advance
Make TimeTo a nullable property like this:
public DateTime? TimeTo { get; set; }
A better solution than the try/catch is to do something like this:
TimeTo = string.IsNullOrEmpty(R[15].ToString())
? (DateTime?) null
: DateTime.Parse(R[15].ToString());
DateTime is a value type and therefore cannot be assigned null. But...
DateTime.MinValue is a nice replacement for that to help point out to the lack of value.
try { TimeTo = Convert.ToDateTime(R[15].ToString()); }
catch { TimeTo = DateTime.MinValue; }
Another option is to make use of nullable types:
DateTime? TimeTo = null;
And reference it like this:
if (TimeTo.HasValue)
something = TimeTo.Value;
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