Home > Software design >  C# for comparing two lists that may contain null values
C# for comparing two lists that may contain null values

Time:05-27

I am comparing two excel sheets using C#.

I have assigned the sheets to datatables and I hope to compare the values in each cell. I have converted the datatables to lists and I'm iterating through them comparing them. How do I avoid a NullReferenceException if one of the values contains a null?

I am hitting a NullReferenceException at this point in the code:

    if (lst1[i].ToString() != lst2[j].ToString())

Is there a way to guard against nulls here or do I need to handle null values earlier in the code?

Thanks

CodePudding user response:

One good way to do this is to ask if the value is null before call .ToString().

So, would be like:

if (lst1[i] != null && lst2[j] != null && lst1[i].ToString() != lst2[j].ToString())

CodePudding user response:

if (lst1[i]?.ToString() != lst2[j]?.ToString())

More info on the ?. operator

CodePudding user response:

Just test for null before dereferencing lst1[i] and lst2[j]

if(lst1[i] is not null and lst2[j] is not null)
{
     if (lst1[i].ToString() != lst2[j].ToString())
     {
         ...
     }

}
  • Related