Escape Sequence
What is Escape Sequence in C#? The escape sequence is a way of writing our statements in such a way that shows up differently on the screen (Console or Windows Form or Website). If we might already know that if we want to print a string then we need to put them between double quotes (” “), and they show up on the screen without quotes. Image if you want to show up the text on the screen with double quotes then how will you do so?
Let me show you a program and you will come to know what I am talking about.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Escape_Sequences
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to C#");
Console.ReadLine();
}
}
}
The output of the Program
As you can see in the program above, we type the Welcome to C# in double-quotes but they show up without double quotes on the Console screen.
What if you want to show Welcome to C# on the screen with Double Quotes then how will you do so?
The answer to this question is Escape Sequences. There are hundreds of escape sequences are provided by Microsoft in C# but I will show you the demonstration of a few here. I will also give you the list of other sequences so that you can use them according to your need.
Showing Text on the console with Double Quotes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Escape_Sequences
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\"Welcome to C#\"");
Console.ReadLine();
}
}
}
Program Output
Explaination
You can see the something extra with your Welcome to C# string. The \ and ” that combination is to show ” on the screen. Now try to understand the work of \ (backslash) here. Let me show you another example.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Escape_Sequences
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\\Welcome to C#\\");
Console.ReadLine();
}
}
}
Explaination
Here I have put two backslashes and the system took one backslash. The combination of these two special characters is called an escape sequence. I hope you have understood the concept.
I will be providing you more escape sequences so stay tuned.
Take Care!