2

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

3 Answers 3

13

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());
Sign up to request clarification or add additional context in comments.

Comments

5

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;

2 Comments

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.
Excuse me, ?? is the null coalescing operator, in C#.
3

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.