CodeBlanks Logo Icon CodeBlanks

Declaring strings

C# course · Beginner · Lesson 30/116

Learn to declare strings with double quotes and verbatim (@) syntax.

Declaring strings

In C#, text is represented by the string type. To create a string you wrap the text in double quotes ("): string city = "Paris";. Single quotes are only for a single character (char).

You can assign a new value to a string variable later. Writing city = "Lyon"; drops the old value and stores the new one. Everything between the double quotes is taken literally, which is why numbers stay unquoted and text stays inside quotes.

Escape sequences

Some characters cannot be placed directly inside double quotes: a new line, a tab, or the double quote itself. For these you use an escape sequence. A backslash (\) followed by a character gives it a special meaning.

\n is a new line, \t is a tab, \\ is a backslash, \" is a double quote. For example, "Line one\nLine two" prints across two lines.

Exercise Print the city variable

Declare a city variable and set its value to "Paris". Then print city with Console.WriteLine. Use double quotes.

Show example solution
Write string city = "Paris"; and print it with Console.WriteLine(city);
Example solution:
using System;

class Program
{
    static void Main()
    {
        string city = "Paris";
        Console.WriteLine(city);
    }
}

Test yourself

  1. Which is a valid string declaration?

    string name = ...;
    • string name = 'Alex';
    • string name = "Alex";
    • string name = Alex;
    • string name = "Alex;
    Show answer

    string name = "Alex"; — Correct. Double quotes declare a string.

  2. Write the newline escape sequence

    string line = "Line one____Line two";
    Show answer
    string line = "Line one\nLine two";
  3. Match each escape sequence to its meaning

    \n
    New line
    \t
    Tab
    \\
    Backslash
    \"
    Double quote

All lessons in Beginner