C# Verbatim String Literal usage


using System;

namespace TrainingSamples
{
    class Demo
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter user name");
            string userName = Console.ReadLine();

            //Usage of verbatim literal
            string userLoc = @"C:\users\User1\User1Folder";
            Console.WriteLine("Hello {0},Your files are stored in  {1}",                                                userName, userLoc);
            Console.ReadKey();
  }
}
}

/*----Output------
Enter user name
Priya
Hello Priya, Your files are stored in C:\users\User1\User1Folder
-----------------*/

Points to learn from this program

1. C# defines the following character escape sequences:

\' – single quote, needed for character literals.
\" – double quote, needed for string literals.
\\ – backslash.
\0 – Unicode character 0.
\a – Alert
\b – Backspace
\f – Form feed
\n – Newline

Additionally, with these escape sequences, any characters proceeding with \ will be considered as escape sequences by C# compiler and start to throw compile-time errors. 
For example, \s \u \d will be considered as an invalid escape sequence even a programmer wants to use these character combinations intentionally. It can be avoided by using verbatim literals.

2. Any string starting with @ symbol considered verbatim.

3. Basically, the @ symbol tells the string constructor to ignore escape characters and line breaks.

Hint:

Try to remove @ symbol from 
string userLoc = @"C:\users\User1\User1Folder"
check what type of error you are getting.

No comments:

Post a Comment