0

I am trying to use the below line of code to extract necessary data from a list and ingest into a different list. Most of the time I am able to get this process success. But at some point, I am getting a null reference exception. I did check for null in the first place for the source list.

 List<Employees> marketingEmployeeList = new List<Employees>();
                if (totalEmployeeList != null && totalEmployeeList.Any())
                {
                    marketingEmployeeList = totalEmployeeList.Where(x => x.department ==                     "Marketing").ToList();
                }
                If(marketingEmployeeList.Any())
                {
                    CallMethod(marketingEmployeeList);
                }

My stack trace contains the below

at System.Linq.Enumerable.WhereListIterator1.ToList() at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)

Previously I didnot check null for totalEmployeeList. I got the null error But later even after i checked null I get the null reference error

  • 1
    It potentially means that one of the items in the list is null. – Guru Stron Mar 30 '23 at 07:19
  • What does `totalEmployeeList` contain? Is there any chance it contains nulls? – Panagiotis Kanavos Mar 30 '23 at 07:19
  • 1
    You gain nothing by using `Any()`. This will iterate the source unless it's a List<> or array, in which case it will just check the length. Just call `.Where(..)`. If you want to exclude nulls, use `Where(x => x?.department == "whatever")`. The expression `x?.department` returns `null` if `x` is null and fails the comparison – Panagiotis Kanavos Mar 30 '23 at 07:21
  • You can simplify all the code and avoid an extra allocation with `var marketingEmployeeList = totalEmployeeList?.Where(x => x?.department == "something").ToList(); if (marketingEmployeeList is !=null ) { CallMethod(...); }`. The null-safe operators `?.` return null if the argument on the left is null instead of throwing. The compiler is smart enough at least in C# 11 to understand that the `marketing..` variable isn't null inside the branch and won't complain if `CallMethod` requires a non-nullable argument – Panagiotis Kanavos Mar 30 '23 at 07:24

0 Answers0