C# ยท Chapter 12 of 46

C# Strings & Methods

A string in C# is a sequence of characters used to represent text. Strings are enclosed in double quotes and have many built-in methods for manipulating text.

Strings in C# are immutable, meaning once created, a string's value cannot change. Methods like ToUpper(), Trim(), and Substring() return a new string rather than modifying the original.

Syntax
string s = "Hello";
s.Length;
s.ToUpper();

Common string methods

Length gives the number of characters, ToUpper()/ToLower() change case, Trim() removes whitespace from the ends, and Replace() swaps out text. Substring() extracts part of a string.

Combining strings

Strings can be joined with the + operator, or with string.Concat(). Since strings are immutable, each combination creates a new string object in memory.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    string greeting = "Hello, World!";
    Console.WriteLine(greeting.Length);
    Console.WriteLine(greeting.ToUpper());
  }
}
Output
13
HELLO, WORLD!

Length returns the character count, and ToUpper() returns an uppercase copy.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    string s = "  Hello  ";
    Console.WriteLine(s.Trim());
    Console.WriteLine(s.Trim().Replace("Hello", "Hi"));
  }
}
Output
Hello
Hi

Trim() removes leading/trailing spaces, and Replace() substitutes text.

Key points

  • Strings are sequences of characters enclosed in double quotes.
  • Strings are immutable โ€” methods return new strings.
  • Length gives the character count of a string.
  • Common methods include ToUpper(), ToLower(), Trim(), and Replace().
๐Ÿ’ก Note: Because strings are immutable, repeatedly concatenating strings in a loop can be slow; use StringBuilder for heavy string building.

๐Ÿ“ Quick Quiz

1. What does the Length property return?

2. Are C# strings mutable or immutable?

3. Which method removes whitespace from both ends of a string?