var statusdiscount = x.firstordefault().statusdiscount; make it safe in csharp

To make the code safe, you can use the null-conditional operator ?. and the null-coalescing operator ??. Here is an example:

main.cs
var statusDiscount = x?.FirstOrDefault()?.StatusDiscount ?? 0;
63 chars
2 lines

In this code, we first use the null-conditional operator ?. to check if x is not null before calling the FirstOrDefault() method. If x is null, then FirstOrDefault() will not be called and statusDiscount will be set to 0.

Next, we again use the null-conditional operator ?. to check if the result of FirstOrDefault() is not null before accessing its StatusDiscount property. If the result is null, then statusDiscount will be set to 0.

Finally, we use the null-coalescing operator ?? to return 0 if StatusDiscount is null, which should not happen if it is a value type.

By using these operators, we can avoid null reference exceptions and make our code safer.

gistlibby LogSnag