๐ŸŽ“ A1Learner
๐Ÿ”

C# Strings

A string is a type that holds text. A string value sits in double quotes and can hold letters, digits, and spaces.

Joining two names

The + sign joins strings end to end. A space string sits between the two names.

using System;

class Program
{
    static void Main(string[] args)
    {
        string first = "Hana";
        string last = "Kim";
        Console.WriteLine(first + " " + last);
    }
}

Join order matters

Joining runs from left to right. Numbers before the first string add up, and numbers after it become text.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("10" + 20 + 30);
        Console.WriteLine(10 + 20 + "30");
    }
}

Values inside a string

A $ before the quotes lets braces hold a value. The F2 specifier in the second line prints two decimal places.

using System;

class Program
{
    static void Main(string[] args)
    {
        string name = "Hana";
        double price = 9.9;
        Console.WriteLine($"Name: {name}");
        Console.WriteLine($"Price: {price:F2}");
    }
}

Comparing string text

The == sign compares the text inside two strings. Even a string built by joining matches a string written out in full.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("abc" == "abc");
        Console.WriteLine(("ab" + "c") == "abc");
    }
}

Quotes and new lines

A backslash before a quote keeps that quote inside the string. The pair \n breaks the text onto a new line.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("She said \"Hi\"");
        Console.WriteLine("One\nTwo");
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        string name = "Hana";
        double balance = 42.5;
        Console.WriteLine($"Hello, {name}. Your balance is {balance:F2}.");
    }
}

Key points

  • A string holds text and sits in double quotes.
  • The + sign joins strings end to end.
  • Joining runs left to right, and the first string turns the rest into text.
  • A $ before the quotes opens holes, and braces mark each hole.
  • A format specifier like F2 inside a hole sets two decimal places.
  • The == sign compares the text of two strings.

In this example, the string opens with a $ sign, so the braces hold values. The name Hana fills the first hole. The balance 42.5 fills the second hole, and F2 prints it as 42.50.

Note

String equality in C# compares the text itself. Some languages compare where the text is stored instead.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

What does 10 + 20 + "30" print?