Kevin
Kevin

Reputation: 125

String switch in Razor markup with colon in case statement causes error "unterminated string literal"

When I want to use a colon ":" in my string switch case statement I get the error "unterminated string literal", how can I fix this and why does it give the error?

Code:

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

If fixed it by doing this but don't find it a good solution:

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

EDIT:MVC Razor syntax are used

Upvotes: 6

Views: 963

Answers (2)

Cristian Lupascu
Cristian Lupascu

Reputation: 40566

Weird bug.

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

In your case, the code could be:

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

Upvotes: 3

JLRishe
JLRishe

Reputation: 101730

How about if you define values as constants in a utility class and then refer to those constants instead of having 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;
 }

Upvotes: 4

Related Questions