Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert null or empty string to datetime var?

Tags:

c#

winforms

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

like image 922
Gold Avatar asked Nov 22 '25 09:11

Gold


2 Answers

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());
like image 127
Chris Conway Avatar answered Nov 24 '25 21:11

Chris Conway


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;