1

How can we avoid null exceptions when using Lambda queries? In the below code when InstallationDateType is null I get an exception. How do I tackle with this?

foreach (AvailableDate availableDate in installationDatesResponseRootObject.Response
              .InstallationDatesResponse
              .AvailableDates
              .Where(a => 
                  a.InstallationDateType.ToString().ToUpper() == Constants.InstallationDateTypeDish))
{
    //Do Something
}
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
zaria khan
  • 333
  • 3
  • 8
  • 18
  • You can check if it has value before you start your for loop –  Dec 08 '16 at 11:42
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – MakePeaceGreatAgain Dec 08 '16 at 11:44

4 Answers4

3

Try to use Null-Conditional Operator ?. introduced in C# 6.

In your example it would be

a.InstallationDateType?.ToString().ToUpper().Equals(Constants.InstallationDateTypeDish)
slanto
  • 86
  • 6
3

Check if installationDatesResponseRootObject, Response, InstallationDatesResponse, AvailableDates aren't nulls. Then change your LINQ into this:

 installationDatesResponseRootObject.Response.InstallationDatesResponse.AvailableDates.Where(a => a.InstallationDateType!=null && a.InstallationDateType.ToString().ToUpper() == Constants.InstallationDateTypeDish))
WholeLifeLearner
  • 455
  • 4
  • 19
2

To elaborate on my comment, here is an example:

var items = installationDatesResponseRootObject.Response.InstallationDatesResponse.AvailableDates
    .Where(a => a.InstallationDateType?.ToString().ToUpper() == Constants.InstallationDateTypeDish);
if (items.Any())
    foreach (var item in items)
    {
          //Do something
    }

Note that this is only an example. There are better ways to check if the IEnumerable is empty or not.

  • This will still result in a `NullReferenceException` because if `InstallationDateType` is null then `.ToString()` will fail. – Scott Bamforth Dec 08 '16 at 12:00
  • 1
    @ScottBamforth you're correct. Fixed my answer with help from slanto. –  Dec 08 '16 at 12:01
1

The issue is because you are called .ToString() on a null reference, so you need to check for this first.

There are a few different ways of checking. If you're using the latest C# then you're probably better off using the Null-Conditional Operator ?. introduced in C# 6 as mentioned by slanto.

If you are using an older version of C# then you can just do it in your Where method as below.

foreach (AvailableDate availableDate in installationDatesResponseRootObject.Response.InstallationDatesResponse.AvailableDates.Where(a => a.InstallationDateType != null && a.InstallationDateType.ToString().ToUpper() == Constants.InstallationDateTypeDish))
{
    //Do Something
}

Hope that helps.