Search code examples
c#asp.net-corerazor

C# 9 relational pattern in switch expression in ASP.NET Core Razor CSHTML


A switch expression something like:

string c = b.Date.CompareTo(now.Date) switch { < 0 => "before", > 0 => "after", _ => "today" };

is valid C# 9.0, but it seems to confuse Razor:

@{
    string c = b.Date.CompareTo(now.Date) switch { < 0 => "before", > 0 => "after", _ => "today" };
}

I get an error at the < (less than) symbol

The element "" was not closed' RZ1025

It's not the less than itself -

@{
    if (1 < 2) {...}
}

is fine.

Obviously, I could replace the switch with an if/elseif/else set, but I'd like to use the more compact version if I can.


Solution

  • You can workaround by using parenthesis (or just by moving this logic into some function outside the Razor markup, for example extension one or possibly encapsulating it in a tag helper):

    @{
        string c = DateTime.Now.CompareTo(DateTime.Now.Date) switch 
        {
            (< 0) => "before", 
            (> 0) => "after", 
            _ => "today" 
        };
    }
    

    UPD

    It seems that this is a known Razor compiler bug.