Extension Methods
Add discoverable operations to existing types.
Introduction
Extension methods are static methods called with instance syntax.
The this modifier on the first parameter declares an extension target. The original string type is not modified.
Runnable C# example
Program.cs
using System;
static class StringExtensions
{
public static string Truncate(this string value, int length)
=> value.Length <= length ? value : value[..length] + "…";
}
class Program
{
static void Main() => Console.WriteLine("CodeUtility".Truncate(4));
}
Code…Practice with the debugger
Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Title Case Capitalize the first letter of every word. Easy
- Acronym Generator Create an acronym from the first letter of every word, in uppercase. Easy