C# String

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

Creating a string variable using the keyword string is a common practice to do any manipulations to a string. 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.String class. The string is immutable, and it can be created objects in different ways:

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

The syntax of the C# strings is as shown below

//String declaration
string str;

//initializing to null
string str = null;

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

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

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

C# String Example

In case if we want to print the string 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 string in double-quotes.

using System;

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

OUTPUT

C# String 1

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

Escape SequenceRepresent
\aBell(alert)
\bBackspace
\fFormfeed
\nNew Line
\rCarriage Return
\tHorizontal tab
\vVertical tab
\’Single quotation mark
\”Double quotation mark
\\Backslash
\?Literal question mark
\ oooASCII character in octal notation
\x hhASCII character in hexadecimal notation