Search code examples
c#stringunicode-escapes

How do I include a string in an escape sequence in c#


I have a string which is a combination of variables and text which looks like this:

string str = $"\x0{str2}{str3}";

As you can see I have a string escape sequence of \x, which requires 1-4 Hexadecimal characters. str2 is a hexadecimal character (e.g. D), while str3 is two decimal characters (e.g. 37). What I expect as an outcome of str = "\x0D37" is str to contain , but instead I get whitespace, as if str == "\x0". Why is that?


Solution

  • As per the specification, an interpolated string is split into separate tokens before parsing. To parse the \x escape sequence, it needs to be part of the same token, which in this case it is not. And in any case, there is simply no way the interpolated part would ever use escape sequences, as that is not defined for non-literals.

    You are better off just generating a char value directly, albeit this is more complex

    string str = ((char) (int.Parse(str2 + str3, NumberStyles.HexNumber))).ToString();