0

I have a List of Entity Framework DAL objects where I am using a query parameter string that can include commas. I am trying to get all objects from the DAL List that satisfy the values in the query parameter string.

I have the following Linq statement that yields what I am expecting:

dalList = dalList
   .Where(aa => queryParamString.Split(',')
      .Any((x => (aa.GetType().GetProperty(kvp.Key).GetValue(aa, null)).ToString().ToLower() == x.ToLower())))
   .ToList();

The above statement works fine if the list does not contain a null value for the reflected property.

How can I include a null check into this Linq statement to avoid the NullReferenceException on the first ToString() method call?

Edit: kvp.Key is a string representation to a database column

Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
davedno
  • 349
  • 1
  • 5
  • 15
  • 1
    `?.ToString()?.ToLower()` – Renat Feb 25 '21 at 19:46
  • 1
    @Renat That appeared to work. If you post as an answer with a simple explanation as to how the ? operand is behaving here I would gladly upvote and accept the answer. – davedno Feb 25 '21 at 19:57
  • `?.` is one of the [null-conditional operators](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-). – NetMage Feb 25 '21 at 20:19
  • Second duplicate says VB.NET, but of course the exact same syntax exists in C#. – Peter Duniho Feb 25 '21 at 20:42

1 Answers1

2

A null-conditional operator ?. could be used to make null checks more concise and to avoid null reference exception.

From MSDN a?.x is being evaluated as:

  • If a evaluates to null, the result of a?.x ... is null.
  • If a evaluates to non-null, the result of a?.x ... is the same as the result of a.x ...

So because .GetValue(aa, null) can return null, to avoid null reference exception in calling ToString() on null we can use .GetValue(aa, null)?.ToString(), which in case of null value just returns null without NRE.

Then even if ?. operator is a short-circuiting operator, ToString() can return null in general, so it's better to use null conditional operator again in ToString()?.ToLower(). Which turns into:

GetValue(aa, null)?.ToString()?.ToLower() == x.ToLower()

and == (string equality operator here) allows for nulls as parameters so we are safe from null reference exception here.

Renat
  • 7,718
  • 2
  • 20
  • 34
  • 1
    I guess it is best to be sure, but Microsoft recommendation is that `ToString` should not return `null` even though the return type is `string?` presumably for backwards compatibility (perhaps they can fix that someday). – NetMage Feb 25 '21 at 20:25