C#
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented C#
-
Section 4: Working with Data
-
Section 5: Error Handling
-
Section 6: Delegates and Events
-
Section 7: Async Programming
-
Section 8: More Language Features
-
Section 9: File I/O and Serialization
-
Section 10: Networking in .NET
-
Section 11: The .NET Ecosystem
-
Section 12: Memory and Performance
-
Section 13: Concurrency Beyond Async
-
Section 14: Reflection and Attributes
-
Section 15: Testing and Best Practices
-
Section 16: Design Patterns in C#
-
Section 17: Standard Library Deep Dive
-
Section 18: Data Structures and Algorithms in C#
-
Section 19: GUI and Desktop Development Overview
-
Section 20: Practical Projects
-
Section 21: More Practice Exercises
-
Section 22: More Standard Library and Text Processing
-
Section 23: More Design Patterns
-
Section 24: More Projects
-
Section 25: Interview Practice
-
Section 26: C# Keywords Reference (Modifiers)
-
Section 27: C# Keywords Reference (Statements)
-
Section 28: C# Keywords Reference (Operators)
-
Section 29: BCL: System.Collections.Generic
-
Section 30: BCL: System.Linq
-
Section 31: BCL: System.Threading
-
Section 32: BCL: System.IO
-
Section 33: BCL: System.Text and System.Text.Json
-
Section 34: BCL: System.Net.Http
-
Section 35: C# Language Specification Topics
-
Section 36: More Practice Exercises
-
Section 37: More Async Patterns
-
Section 38: More BCL: System.Reflection and System.Diagnostics
-
Section 39: Nullable Reference Types In Depth
-
Section 40: C# Records and Pattern Matching In Depth
-
Section 41: Dependency Injection Deep Dive
-
Section 42: More Interview and Whiteboard Practice
115: String Methods and StringBuilder
I see this all the time when I'm reviewing junior code: a for loop that builds a large string using the += operator. It looks clean, it's intuitive, and it works perfectly fine when you're only dealing with five or ten items. The misconception is that C# is "smart enough" to just append the new text to the existing memory location of that string.
The Myth that += is Just a Shortcut
It isn't. In C#, strings are immutable. When you write myString += " next part";, you aren't actually adding text to the end of the original string. Instead, the runtime creates a brand new string object in memory, copies the old content over, appends the new content, and then throws the old string away for the Garbage Collector to clean up.
// This is a performance disaster in a real application
string report = "";
for (int i = 0; i < 10000; i++)
{
// Every single iteration creates a whole new string object
report += $"Line {i}: System status OK\n";
}
If you do this with 10,000 iterations, you've just created 10,000 string objects. Most of them are garbage immediately after they are created. On a small scale, you won't notice. In a high-traffic production environment, this is how you create memory pressure and trigger massive GC pauses that make your app stutter.
The Power of the Mutable Buffer
This is exactly why StringBuilder exists. Think of it as a dynamic buffer—a workspace where you can throw text, chop it up, and append to it without constantly allocating new memory. It only creates the final string once, at the very end, when you call ToString().
using System.Text;
var logBuilder = new StringBuilder();
for (int i = 0; i < 10000; i++)
{
// This modifies the internal buffer rather than creating a new object
logBuilder.AppendLine($"Line {i}: System status OK");
}
string finalReport = logBuilder.ToString();
I generally follow this rule of thumb: if you're concatenating more than three or four strings, or if you're doing it inside any kind of loop, reach for the StringBuilder. Your memory profiler will thank you.
Cleaning Up the Mess with String Methods
While StringBuilder is for building, the String class provides a massive library of methods for manipulating existing text. You'll find yourself using these constantly to sanitize user input or parse data.
Take a look at these common heavy-hitters:
- Trim(), TrimStart(), TrimEnd(): Essential for removing accidental whitespace from the ends of a string.
- Replace("old", "new"): Great for swapping placeholders or cleaning up forbidden characters.
- Split('delimiter'): Turns a single string into an array. Be careful here; splitting a massive string can create a lot of small string objects.
- Substring(startIndex, length): Grabs a specific chunk of a string. Just remember that it throws an exception if you try to grab more characters than the string actually contains.
string rawInput = " ERROR: Database Timeout [Code: 404] ";
// Clean up the edges
string cleanInput = rawInput.Trim();
// Isolate the error code
// We find the index of the bracket and slice from there
int start = cleanInput.IndexOf("[") + 1;
int length = cleanInput.IndexOf("]") - start;
string errorCode = cleanInput.Substring(start, length);
Console.WriteLine($"Cleaned Error: {errorCode}"); // Output: Code: 404
One quick tip: Always check for null or use the null-conditional operator before calling these methods. There is nothing more annoying than a NullReferenceException because a user left a text field empty.
📋 Practical Task
Build a CSV-to-Summary Log Generator
You have been given a raw string containing several rows of comma-separated values (CSV). Each row represents a system event: Timestamp, Level, Message. However, the raw data is "dirty"—it has leading/trailing whitespace and inconsistent casing.
Your Task: Write a program that parses this raw string and uses a StringBuilder to create a formatted summary report.
Requirements:
- Input string:
" 2023-10-01, info, System Started \n 2023-10-01, warn, Low Disk Space \n 2023-10-02, error, Connection Failed " - For each line:
- Split the line by the comma.
- Trim the whitespace from each piece.
- Ensure the "Level" (info, warn, error) is converted to UPPERCASE.
- Append it to a
StringBuilderin the format:[LEVEL] Date: Message
- Output the final resulting string to the console.
Expected Output:
[INFO] 2023-10-01: System Started
[WARN] 2023-10-01: Low Disk Space
[ERROR] 2023-10-02: Connection Failed
There are no comments for now.