# Modern C# Features — C#/.NET

Source: https://www.skillbyai.com/en/dotnet/p-modern

> Recognise and use features from recent C# versions.

## Less ceremony, same safety

Recent C# versions removed a lot of boilerplate. **File-scoped namespaces** (`namespace Shop;`) remove a level of indentation. **Global usings** and implicit usings declare common namespaces once. **Raw string literals** (`"""..."""`) hold JSON, SQL or regex without escaping. **Records**, **init** and **required** members model data. **Primary constructors** on classes and structs reduce constructor code, and **collection expressions** create collections uniformly. **Pattern matching** keeps growing: list patterns, extended property patterns. C# 13 brought `params` collections and the new `Lock` type. **C# 14**, shipped with .NET 10, adds the **`field`** keyword for property backing fields, **extension members** (extension blocks that can declare extension properties as well as methods), **null-conditional assignment** (`customer?.Order = order;`) and implicit conversions to spans. Use new features where they make code clearer, and keep a consistent style across the team.

## A few modern features together

Raw strings, file-scoped namespaces, the field keyword and an extension block.

```cs
namespace Shop;

public class Product
{
    public required string Sku { get; init; }

    public decimal Price
    {
        get;
        set => field = value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value));
    }
}

public static class ProductExtensions
{
    extension(Product p)
    {
        public bool IsFree => p.Price == 0;
    }
}

public static class Queries
{
    public const string TopProducts = """
        SELECT sku, price
        FROM products
        WHERE price > @min
        ORDER BY price DESC
        """;
}
```

## A newer model of the same car

Modern C# is a newer model of the same car: power steering and parking sensors, but the same engine underneath. Older code still drives; newer features just make everyday trips smoother.

**Quiz:** What does the C# 14 `field` keyword refer to inside a property accessor?

- [ ] A database column
- [x] The compiler-generated backing field of that property
- [ ] Any field in the class
- [ ] A static field

*Answer:* The compiler-generated backing field of that property. field gives accessors access to the auto-generated backing field, so you can add logic without declaring one.
