Lesson 2 of 40
C# Language
Intermediate
35 min
C# 14 New Language Features
Explore the powerful new language features in C# 14 including primary constructors improvements, collection expressions, and interceptors.
Part 1: Primary Constructors (Enhanced)
C# 14 extends primary constructors to all classes — not just records. Parameters are available throughout the class body:
public class UserService(IRepository repo, ILogger logger)
{
public async Task<User> GetAsync(int id) =>
await repo.FindAsync(id);
}
{
public async Task<User> GetAsync(int id) =>
await repo.FindAsync(id);
}
Part 2: Collection Expressions
Collection expressions unify array/list/span creation syntax:
int[] nums = [1, 2, 3, 4, 5];
List<string> tags = ["csharp", "dotnet"];
Span<int> span = [..nums, 6, 7];
// Spread operator works across all collection types
List<string> tags = ["csharp", "dotnet"];
Span<int> span = [..nums, 6, 7];
// Spread operator works across all collection types
Part 3: Interceptors (Production Ready)
Interceptors allow source generators to redirect method calls at compile time — powerful for frameworks:
// In a source generator:
[InterceptsLocation("Program.cs", line: 5, character: 3)]
public static void LoggingInterceptor(this IService s)
{
Console.WriteLine("Intercepted call");
s.OriginalMethod();
}
[InterceptsLocation("Program.cs", line: 5, character: 3)]
public static void LoggingInterceptor(this IService s)
{
Console.WriteLine("Intercepted call");
s.OriginalMethod();
}
Part 4: Field keyword in Properties
The new
field keyword in property accessors eliminates backing field boilerplate:public string Name
{
get => field;
set => field = value?.Trim() ?? throw new ArgumentNullException();
}
{
get => field;
set => field = value?.Trim() ?? throw new ArgumentNullException();
}