linq prevent nullexception in csharp

To prevent NullReferenceException while using LINQ queries, we can perform null-checking using the following methods:

  1. Null-conditional Operator (?):
main.cs
   var result = collection?.Where(x => x.Property == value);
61 chars
2 lines

In the above code, a check is performed on the collection object. If the collection is null, the condition returns null without throwing an exception.

  1. Nil-Coalescing Operator (??):
main.cs
   var result = collection?.Where(x => x.Property == value) ?? Enumerable.Empty<CollectionType>();
99 chars
2 lines

In the above code, a check is performed on the collection object. If the collection is null, then an empty collection of the same type is returned.

  1. Classic if-statement:
main.cs
   if(collection != null)
   {
      var result = collection.Where(x => x.Property == value);
   }
99 chars
5 lines

In the above code, we are performing a null check on the collection object before executing the LINQ query. This is a classic way of preventing NullReferenceException.

  1. DefaultIfEmpty() Method:
main.cs
   var result = collection?.Where(x => x.Property == value).DefaultIfEmpty();
78 chars
2 lines

In the above code, DefaultIfEmpty() method is used to return either a collection with one default value if source collection is empty or the result of the query if not empty.

It is essential to perform null checks on objects and variables to avoid NullReferenceException while using LINQ queries.

gistlibby LogSnag