x.firstordefault().statusdiscount; add default value to prevent null exception in csharp

To add a default value to x.FirstOrDefault().StatusDiscount;, you can use the null-conditional operator (?.) and the null-coalescing operator (??). Null-conditional operator allows the code to skip further property/method access if an object reference is null. Null-coalescing operator allows returning a default value when the retrieved value is null.

Here's an example:

main.cs
var defaultDiscount = 0.0; // set default value here
var statusDiscount = x.FirstOrDefault()?.StatusDiscount ?? defaultDiscount;
129 chars
3 lines

In the example above, if x.FirstOrDefault() returns null, null-conditional operator will return null, and the null-coalescing operator will return the default value of 0.0. If x.FirstOrDefault() returns an object, it will access the StatusDiscount property without causing a null reference exception.

gistlibby LogSnag