I have the following, but it's failing with a NullReferenceException
:
<td>@item.FundPerformance.Where(xx => fund.Id == xx.Id).FirstOrDefault().OneMonth ?? -</td>
OneMonth
is defined as
public virtual decimal? OneMonth { get; set; }
and its value is null at the time that it fails.
I thought the Null Coalesce operator would test if its null and if so, return the value to the right of the operator?
What do I need to change to make this work?
operator is known as Null-coalescing operator. It will return the value of its left-hand operand if it is not null. If it is null, then it will evaluate the right-hand operand and returns its result. Or if the left-hand operand evaluates to non-null, then it does not evaluate its right-hand operand.
Uses of Null Coalescing Operator: It is used to replace the ternary operator in conjunction with the PHP isset() function. It can be used to write shorter expressions. It reduces the complexity of the program. It does not throw any error even if the first operand does not exist.
Nullable types work as a connector between a database and C# code to provide a way to transform the nulls to be used in C# code. Null Coalescing operators simplify the way to check for nulls and shorten the C# code when the developer is dealing with nulls.
The razor syntax, as you wrote it, ends at "OneMonth". The ?? are interpreted as text. To have it interpreted as razor, you must wrap the whole statements in () like this:
<td>@(item.FundPerformance.Where(xx => fund.Id == xx.Id).FirstOrDefault().OneMonth ?? "-")</td>
This will still get you an error: the left operator is a decimal and the right operator is a string. So you can either render a zero instead of "-" or use ternary operator, with OneMonth.Value.ToString() as left value and "-" as right value.
It's nothing to do with MVC or Razor.
FundPerformance.Where(xx => fund.Id == xx.Id).FirstOrDefault()
will return null if there is no element that matches, null does not have a OneMonth porperty so you will get a null ref exception. You cannot use the ?? operator as it is not OneMonth that is null, it is the result of FirstOrDefault()
.
To test change your code to
FundPerformance.Where(xx => fund.Id == xx.Id).First().OneMonth ?? -</td>
If you get a "sequence contains no elements" exception instead then you know that is your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With