C# Generic Constraints
Require an interface capability instead of using reflection to guess whether a method exists.
How it works
A generic constraint states what operations or type properties an implementation may rely on. An interface constraint allows the method body to call that interface without runtime casts. Constraints describe types, not every valid value, so a named capability still needs a behavioural contract. Avoid imposing a new() constraint merely to hide dependency creation when the caller should provide an already configured object. A method accepting an interface directly may be simpler when preserving a concrete type adds no value.
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)
{
Console.WriteLine(Label(new WorkshopCode("W-17")));
}
internal static string Label<T>(T value) where T : ILabelled
{
return value.Label;
}
}
internal interface ILabelled { string Label { get; } }
internal sealed record WorkshopCode(string Label) : ILabelled;
Expected result
W-17
WorkshopCode satisfies the interface and the method uses its documented Label property. The record owns immutable text under this fixture. Null input remains a separate concern for a public API, especially when T is a reference type. Add a null check or an appropriate caller contract instead of assuming that a type constraint guarantees a live object.
Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.