null shorthand in C#?

Is there a way to make this line shorter?

bool pass = d != null && d["k"] != null && (bool)d["k"];

Note: "k" is actually "a longer id"; I replaced it to make it more readable in this post. Many of your suggestions don't check whether d is null.

Jon Skeet
people
quotationmark

A combination of the null-conditional and null-coalescing operators should work here:

bool pass = (bool) (d?["k"] ?? false);

To clarify:

  • If d is null, d?["k"] is null
  • If d?["k"] is null, d?["k"] ?? false is false (boxed as object)
  • The result is then cast

An alternative would be to cast before the null-coalescing operator, but to cast to a nullable type:

bool pass = ((bool?) d?["k"]) ?? false;

Note that the null-conditional operator was introduced in C# 6.

people

See more on this question at Stackoverflow