C# Strings

C# Strings

Strings are used for storing text. A string variable contains a collection of characters surrounded by double quotes. In C#, strings are incredibly powerful and come with many built-in methods to manipulate them.


String Length

To find out how many characters are inside a string, you can use the Length property.

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Console.WriteLine("The length of the txt string is: " + txt.Length); // Outputs 26

ToUpper() and ToLower()

You can easily convert any string to all uppercase or all lowercase letters using the ToUpper() and ToLower() methods.

string txt = "Hello World";
Console.WriteLine(txt.ToUpper());   // Outputs "HELLO WORLD"
Console.WriteLine(txt.ToLower());   // Outputs "hello world"

String Concatenation vs Interpolation

Combining two or more strings is a very common task. There are two popular ways to do this in modern C#:

1. Concatenation

You can use the + operator to join strings together.

string firstName = "John ";
string lastName = "Doe";
string name = firstName + lastName;
Console.WriteLine(name);

2. String Interpolation (Modern Approach)

String interpolation substitutes values of variables directly into placeholders in a string. To use it, place a dollar sign ($) right before the starting quote, and wrap variables in curly braces {}. This is often much easier to read!

String Interpolation

using System;

class Program { static void Main() { string firstName = "John"; string lastName = "Doe"; // Using string interpolation string name = $"My full name is: {firstName} {lastName}"; Console.WriteLine(name); } }


Exercise

?

Which character is used to denote an interpolated string in C#?