0

I would like for the VS compiler to raise an error when I define a string using escape literals. I am using VS 2017 .NET 4.7. In the previous version (VS2010), I was getting the error

CS1009: unrecognized escape sequence.

if I defined a string like:

string foo="d:\test";

Currently, I didn't find any way to enable it. Tried to go to Project Properties > Code Analysis and open all rules, but couldn't find CS1009 at all.

The reason why I would like this behavior is that after I defined a variable as I mentioned above, I, later on, used it in a Path.Combine method, the method that raised an exception due to illegal characters in path (tab).

I know that I can use double backslashes for escaping the backslash or even use @ in front of the string, but I would like in the future not to be allowed to define a string like this.

Can you please help me with this?

Thanks, George

frido
  • 13,065
  • 5
  • 42
  • 56
  • 2
    It's not clear what behavior you are looking for. `\t` is a valid escape sequence, meaning the tab character (as you know). The compiler does not know that this string happens to represent a file path where tab is not allowed. – 500 - Internal Server Error Aug 01 '19 at 12:31
  • That is correct. it is actually no problem with the compiler itself or with the ruleset. If for example I try to use ''''Path.Combine("d:\test")''' I actually get the compiler error CS1009. This is because when creating a path, it cannot have invalid characters, like \n or \t – M. George Aug 01 '19 at 12:54
  • Then I would ask, if I have a variable defined as: string foo="d:\test\bar", how can I use this variable in a Path.Combine? Replace("//","////") doesn't work. – M. George Aug 01 '19 at 12:59
  • You can't as is. You'll have to prefix with `&` to disable the escapement interpretation, which is enabled by default, or else use escapes, i.e. `\\\`. That's just how it is. – 500 - Internal Server Error Aug 01 '19 at 13:01
  • Why is this a problem? - these are source code literals, after all, so it's not like you have a ton of them that need to be touched up manually ... or? – 500 - Internal Server Error Aug 01 '19 at 13:04
  • it is actually no problem. In my application I am currently hardcoding these paths and found out this issue. however, I will take this path from an xml file, and when reading from the xml file, the backslashes will be escaped. I was just curious how this can changed. @500-InternalServerError. I think in your previous comment you were referring to @ for disabling the escapement interpretation – M. George Aug 01 '19 at 13:26

1 Answers1

0

I guess you need code contracts to specify, how to treat your string in compile-time. What you written here is perfectly valid string with TAB character. Check out this question too.