Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Null Coalesce operator to work in ASP.NET MVC Razor?

Tags:

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?

like image 639
DaveDev Avatar asked Dec 09 '11 10:12

DaveDev


People also ask

How do you use null coalesce in C#?

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.

What is use of null coalesce operator?

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.

What is nullable types and null coalescing operator in C#?

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.


Video Answer


2 Answers

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.

like image 182
Matteo Mosca Avatar answered Sep 19 '22 10:09

Matteo Mosca


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.

like image 25
Ben Robinson Avatar answered Sep 23 '22 10:09

Ben Robinson