Razor markup string switch with a colon in the case argument causes an "unterminated string literal" error

When I want to use the colon ":" in my case statement of a string operator, I get the error message "unterminited string literal", how can I fix it and why does it give an error?

code:

@switch (stringText) { case "aaaa:ggg": Do something... break; case "bbbb:ggg": Do something else... break; } 

If fixed, by doing this, but not finding it a good solution:

 const string extra = ":ggg"; @switch (stringText) { case "aaaa" + extra: Do something... break; case "bbbb" + extra: Do something else... break; } 

EDIT: uses MVC Razor syntax

+6
source share
2 answers

How about defining constants in a utility class, and then referring to these constants instead of string literals in the switch statement?

 class Constants { public const string Aaaa = "aaaa:gggg"; public const string Bbbb = "bbbb:gggg"; } 

...

 @switch (stringText) { case Constants.Aaaa: Do something... break; case Constants.Bbbb: Do something else... break; } 
+4
source

A strange mistake.

Here's another workaround: if you don't want to define constants, you can use the \x3A escape sequence to get colons in your string literals, so that this doesn't interfere with checking the razor syntax.

In your case, the code could be:

 @switch (stringText) { case "aaaa\x3Aggg": Do something... break; case "bbbb\x3Aggg": Do something else... break; } 
+3
source

All Articles