C# Extension Methods
Write a small pure label helper while keeping validation responsibilities explicit.
How it works
An extension method provides instance-style call syntax for a static method in an appropriate static class. It does not modify the target type’s implementation, gain private access or change ownership. Traditional this-parameter extension syntax remains useful in this C# 14 course; newer extension-block syntax is a separate authoring choice, not required to understand the contract. Keep extension names specific so they do not hide surprising side effects behind an apparently harmless property-like operation.
Run it locally
Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-buildUse the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.
Example
using System;
internal static class Program
{
private static void Main(string[] args)
{
string code = "W-17";
Console.WriteLine(code.AsBookingLabel());
}
}
internal static class BookingLabels
{
public static string AsBookingLabel(this string code)
{
ArgumentException.ThrowIfNullOrWhiteSpace(code);
return "Booking " + code;
}
}
Expected result
Booking W-17
The static helper validates its input before constructing a new string. It does not mutate code. A public identifier type would be a better home for syntax and length invariants shared by many operations. Keep extensions out of unrelated global namespaces when they would create ambiguous or misleading APIs for callers.
Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.