tags:

views:

79

answers:

3

hi

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

+5  A: 

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;
Developer Art
Another useful way to reference it is with the collapse operator. The expression would look like `TimeTo ?? defaultTimeTo`, resolving to the latter if the former is null.
Steven Sudit
Excuse me, `??` is the null coalescing operator, in C#.
Steven Sudit
+8  A: 

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());
Chris Conway
thank's !! its work !!
Gold
+3  A: 

on a slight tangent, if you are expecting that R[15] may not be a datetime I would suggest TryParse is a better option

if(DateTime.TryParse(R[15].ToString(),out TimeTo))
{
     //TimeTo is set to the R[15] date do stuff you need to if it is good
}
else
{
    //TimeTo is default (i.e. DateTime.MinValue) do stuff for a bad conversion (e.g. log, raise exception etc)
}
Pharabus