XhCode Online Converter Tools

Csharp Escape Unescape



Done Code:
Csharp / C# Escape Unescape

In C#, escaping and unescaping are processes used to handle special characters in strings, ensuring they are stored and transmitted correctly. This is particularly useful when working with strings that may include characters like quotes, backslashes, or newlines.

1. C# Escape
Escaping in C# involves converting characters that have special meanings (like quotes or backslashes) into a format that can safely be included within a string literal.

Common Escape Sequences in C#:
Backslash (\) – To represent a backslash, use \\
Double quotes (") – To include double quotes inside a string, use \"
Newline (\n) – Represents a line break.
Tab (\t) – Represents a horizontal tab.
Carriage return (\r) – Represents a carriage return.
Unicode characters (\u) – Used for special Unicode characters, e.g., \u00A9 for the copyright symbol.
Example:
csharp

string escapedString = "He said, \"Hello!\"\nWelcome to C#.";
Console.WriteLine(escapedString);
Output:

nginx

He said, "Hello!"
Welcome to C#.
In this case:

The double quotes are escaped with \" so they don't end the string.
The newline is escaped with \n.
2. C# Unescape
Unescaping in C# means converting an escaped string back into its original form. This process removes the escape characters, like turning \\ back into a single backslash, and \" back into a regular quote.

In C#, when you have a string with escape sequences that need to be processed, .NET provides built-in methods to unescape them.

For example, System.Text.RegularExpressions.Regex.Unescape() is a method used to unescape escape sequences in a string.

Example of Unescaping:
csharp

string escapedString = "He said, \\\"Hello!\\\"\\nWelcome to C#!";
string unescapedString = System.Text.RegularExpressions.Regex.Unescape(escapedString);
Console.WriteLine(unescapedString);
Output:

nginx

He said, "Hello!"
Welcome to C#.
In this case:

The \\ is replaced with a single backslash.
The \\n is replaced with an actual newline character.
3. Raw String Literals (C# 11 and later)
Starting from C# 11, C# supports raw string literals, which makes it easier to include special characters like backslashes or quotes without needing to escape them.

Example:
csharp

string rawString = """He said, "Hello!"
Welcome to C#!""";
Console.WriteLine(rawString);
Output:

nginx

He said, "Hello!"
Welcome to C#!
This new feature simplifies string handling when dealing with multi-line strings or strings with lots of escape sequences.

Summary:
Escape sequences allow you to represent special characters in a string using backslashes, e.g., \", \\, \n.
Unescape refers to converting escaped characters back to their original form, which can be done using Regex.Unescape().
Raw string literals in C# (available in C# 11 and later) allow you to avoid escaping special characters entirely.

TOP