Skip to main content
C# Fundamentals for Beginners to Advanced
CHAPTER 10 Beginner

Strings in C#

Updated: May 17, 2026
5 min read

# CHAPTER 10

Strings in C#

1. Introduction

Text manipulation is central to almost every application. Whether validating a password, searching a database, or formatting a report, you will work extensively with string. In C#, strings are powerful, but they have a unique memory behavior that every developer must understand to avoid performance bottlenecks.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use built-in String methods for text manipulation.
  • Understand Escape Characters.
  • Explain the concept of String Immutability.
  • Use StringBuilder for high-performance string manipulation.

3. Built-in String Methods

The string class contains dozens of methods to manipulate text easily.
csharp
12345678910111213141516171819
string text = "  Hello World!  ";

// 1. Length property
int len = text.Length; // 16

// 2. ToUpper() and ToLower()
string upper = text.ToUpper(); // "  HELLO WORLD!  "

// 3. Trim() - Removes leading and trailing whitespace
string cleanText = text.Trim(); // "Hello World!"

// 4. Contains() - Checks if text exists inside the string
bool hasWorld = cleanText.Contains("World"); // true

// 5. Replace()
string newText = cleanText.Replace("World", "C#"); // "Hello C#!"

// 6. Substring() - Extracts a portion of the string
string hello = cleanText.Substring(0, 5); // "Hello" (Starts at index 0, grabs 5 chars)

4. Escape Characters

If you want to print a double-quote inside a string, it confuses the compiler because double-quotes are used to define the string itself. You must "escape" special characters using a backslash \.
CharacterMeaningExample
\"Double Quote"He said \"Hello\"."
\nNew Line"Line 1\nLine 2"
\tTab"Column1\tColumn2"
\\Backslash"C:\\Folder\\File.txt"

Verbatim Strings (@): Instead of using \\ for file paths, prefix the string with @ to ignore all escape characters.

csharp
1
string path = @"C:\Folder\File.txt"; // Much cleaner!

5. OOP and Memory: String Immutability (CRITICAL)

In C#, strings are immutable. Once a string is created in the Heap memory, it can NEVER be changed.
csharp
12
string name = "John";
name = name + " Doe"; // What happens here?

When you add " Doe" to "John", C# does NOT modify "John". Instead, it:

  1. 1. Creates a brand new block of memory for "John Doe".
  1. 2. Changes the name variable to point to the new memory.
  1. 3. Leaves the original "John" string in memory until the Garbage Collector deletes it.

If you concatenate strings in a for loop 10,000 times, you will create 10,000 abandoned strings in memory, causing massive lag!

6. The Solution: StringBuilder

When performing heavy string manipulation (like inside loops), use the StringBuilder class. It manages a dynamic buffer and modifies text *in-place* without creating abandoned strings.

*(Requires using System.Text;)*

csharp
1234567891011121314151617181920212223
using System;
using System.Text;

namespace StringBuilderDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creates a mutable string buffer
            StringBuilder sb = new StringBuilder();

            // Very fast! Does not create multiple strings in memory.
            for (int i = 0; i < 1000; i++) 
            {
                sb.Append("Word "); 
            }

            // Convert back to a standard string when finished
            string finalResult = sb.ToString();
        }
    }
}

7. Common Mistakes

  • Using == vs .Equals(): In Java, you must use .Equals() to compare strings. In C#, the == operator is heavily overloaded to compare the actual *value* of the strings safely. if(name == "Admin") is perfectly valid and preferred in C#.
  • Ignoring Case Sensitivity: "apple" == "Apple" is false. Always use .ToLower() before comparing user input.

8. Best Practices

  • Use standard strings and the + operator (or interpolation $"") for simple concatenation (1-5 operations).
  • Always use StringBuilder if you are modifying a string inside a loop.

9. Exercises

  1. 1. Write a program that asks for a user's full name, and prints their initials using Substring().
  1. 2. Given the string "C:\Users\Admin\Desktop", print it to the console using a verbatim string literal (@).

10. MCQs with Answers

Question 1

What property returns the number of characters in a string?

Question 2

Which method removes spaces from the beginning and end of a string?

Question 3

What does it mean that strings are "Immutable"?

Question 4

Which character acts as the escape character in C# strings?

# Answer: b) \
Question 5

How do you print a newline inside a standard string?

Question 6

What does placing an @ symbol before a string do?

Question 7

What class should you use to concatenate strings inside a large loop?

Question 8

Which namespace is required to use StringBuilder?

Q9. Is "HELLO" == "hello" true or false in C#? a) True b) False Answer: b) False (C# strings are case-sensitive)
Question 10

What does text.Substring(0, 3) return if text is "Batman"?

11. Interview Questions

  • Q: Explain String Immutability and why it exists.
  • Q: Describe the exact scenario where you would choose StringBuilder over standard string concatenation.
  • Q: What happens in memory when you execute string s = "A"; s += "B"; s += "C";?

12. Summary

Strings are feature-rich but immutable. Methods like .Trim() and .ToUpper() return brand new strings rather than modifying the original. For heavy text assembly, utilizing StringBuilder is a critical optimization technique to prevent memory bloat and Garbage Collector lag.

13. Next Chapter Recommendation

Up until now, all our code has been trapped inside the Main method. In Chapter 11: Methods and Parameters, we will learn how to break our code into reusable, organized blocks.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·