Jess Wss Jess Wss - 1 month ago 7
C# Question

If condition in C#

I have this code that checks a cell in an Excel file.

var a = worksheet.Cells[i, 4].StringValue;
if (!string.IsNullOrEmpty(a))
{
table.A = (DateTime?)GetResult(UploaddataBase.ProcessDateTime(a, i, null), "A").Value;

if (table.A.Value < table.B.Value)
{
unexpectedExceptions.Add(i.ToString(), string.Format("A should be less than B for row number : {0}", (i + 1)));
}
}


I want to check that if table.B.Value,regardless it exists or not in the file, to check this condition
if (table.A.Value < table.B.Value)


This can be done like this?

if(!string.IsNullOrEmpty(a) && !string.IsNullOrEmpty(b))
else if(string.IsNullOrEmpty(a) && string.IsNullOrEmpty(b))


or it is another whay?

Answer

Presuming that table.A and table.B are of type DateTime?, you could do...

if(table.B.HasValue && table.A.HasValue && (table.A.Value < table.B.Value)
{
    unexpectedExceptions.Add(
        i.ToString(), 
        string.Format("A should be less than B for row number : {0}", (i + 1)));
}