C# String

In C#, it is an object of the System.String class in Dot Net framework. Objects of the String class are immutable (once created cannot be changed). Basically, the string type is a sequence of characters (text).

Creating a variable using the keyword string is a common practice to do any manipulations to that variable or text inside it. But in C#, Strings can also be used as an array of characters.

We can say that the string keyword is an alias name for the System class. Since C# string is immutable, and it can be created objects in different ways:

  • By creating a variable and assigning a literal to it.
  • By using the concatenation operator +.
  • Using the constructor of this class.
  • Calling a method that returns the text or literal.
  • By calling a Format method to convert a value or an object to its text representation.

The syntax of the C# strings is shown below.

string str;

//initializing to null
string str = null;

//Initializing an empty 
string str = “”;
string str = System.String.Empty;

//Initializing a literal
string path = “C:\\Program Files\\Microsoft SQL SERVER”;

//Initializing a using Verbatim literal to improve readability 
string str = @“C:\Program Files\Microsoft SQL SERVER”;

C# String Example

In case we want to print the text in double quotes. For example (“Tutorial Gateway”), then directly, we cannot use them because double quotes have a special meaning in C#. Using Escape sequence \ (backslash), we can print a text in double quotes.

using System;

    class Program
        static void Main()
        string str = "\"Tutorial Gateway\"";
        Console.WriteLine("This is {0}", str);


C# String 1

The following are the various character Escape sequences in C# Programming language to display strings.

Escape SequenceRepresent
\nNew Line
\rCarriage Return
\tHorizontal tab
\vVertical tab
\’Single quotation mark
\”Double quotation mark
\?Literal question mark
\ oooASCII character in octal notation
\x hhASCII character in hexadecimal notation