0
var TravelRoute = MyData.TravelRouteByName(
         parameters.Directions
                   .Where(p => p.TravelRouteId != null)
                   .Select(p => p.TravelRouteId.Value)
                   .Distinct()
                   .ToArray());

I have the sample linq query above. If Directions is null, it will through an exception that ""

Value cannot be null.\r\nParameter name: source

What would be the best way of handling such situations such that no exception is thrown?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
StackTrace
  • 9,190
  • 36
  • 114
  • 202
  • 1
    [Null-conditional operators](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-) or `if(parameters.Directions != null) { var TravelRoute = MyData.TravelRouteByName(parameters.Directions.Where...` – vernou Nov 04 '21 at 13:51
  • @vernou i want the var TravelRoute to be declared outside of the if statement but when i do that it complains that "cannot assign null to an implicitly-typed variable" – StackTrace Nov 04 '21 at 13:55
  • 1
    @StackTrace You have to declare your variable with an explicit type in that case. (TravelRoute TravelRoute = null;) – Tobias Schulte Nov 04 '21 at 14:02
  • @StackTrace don't put everything in a single line. In this case the LINQ query has no reason to be in the same line as `MyData.TravelRouteByName`. If you extract that expression into a separate line it becomes trivial to check whether `Directions` is null *before* executing the query. `if (parameters.Directions != null){ var values=parameters.Directions.Where(....); var TravelRoute=MyData.TrravelRouteByName(values);...}` – Panagiotis Kanavos Nov 04 '21 at 14:05
  • 1
    What should `MyData.TravelRouteByName` do if `Directions` is null? What does the rest of the method do? Perhaps you should validate `parameters` and `Directions` at the start of the method before proceeding – Panagiotis Kanavos Nov 04 '21 at 14:07

1 Answers1

0

This is not exactly a problem with linq only, in your example it's probably simply the first place where you notice Directions being null. Instead of Directions.Where(...) you could use the null conditional Operator ?.: Directions?.Where(...). This way no more methods from your chained calls are executed and you would get null as the arguments to the TravelRouteByName method.

Another approach (which I would personally prefer) would be to completely stay away from null values, which became a lot easier with the release of C# 8: How to enable Nullable Reference Types feature of C# 8.0 for the whole project

Tobias Schulte
  • 716
  • 5
  • 18