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

Time:09-15

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.

CodePudding user response:

You can workaround by using parenthesis (or just by moving this logic into some function outside the Razor markup, for example extension one):

@{
    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.

CodePudding user response:

try this:

@{
  string c =( DateTime.Now.CompareTo(DateTime.Now.Date)>0?1: 
  (DateTime.Now.CompareTo(DateTime.Now.Date))==0?0:-1)).ToString()

  switch { "-1" => "before", "1" => "after", "0" => "today" };
}

Hope this helps!

  • Related