Search code examples
c#.net.net-core

Converting a tab stored as a string into a char in C#


I'm trying to convert a value retrieved from a deserialized XML file into a char.

<Delimiter>\t</Delimiter>

When I deserializing this XML into an object with a string property it becomes:

"\\t"

However, when I try to use the following code to get a char:

char c = Convert.ToChar(stringValue);

I get the exception:

System.FormatException: 'String must be exactly one character long.'

If execute this code, it works:

char c = Convert.ToChar("\t");

How to I convert my string "\\t" into "\t" in order to convert it to a char?

I tried str = str.Replace("\\\\", "\\") but that didn't seem to get rid of the escape backslash.


Solution

  • The literal \t would be interpretted by C# as a single tab (0x9) character before calling .ToChar().

    Additionally, you are NOT getting \\t (three characters) as a result of deserializing that xml. You are getting (\t) (two characters), but the debugger is trying to be overly helpful and escaping the \ escape character when showing it to you. Furthermore, this two character \t string is not the same as a \t literal, because the \ escape character in the literal is parsed at compile time and matched with the t so you end up with a single tab (0x9) character.

    So, how do you convert the two \ and t characters and get the final tab (0x9) single character result?

    You can use Regex.Unescape() for this.

    See it work here:

    https://dotnetfiddle.net/OYE2Nf