Master modern C# features: records, structs, pattern matching with switch expressions, and nullable reference types.
Leverage C# 9+ features for cleaner, safer code.
record and a readonly struct, then demonstrate value equality and the with expression.public record Person(string Name, int Age);
2. Create a readonly struct:
public readonly struct Point
{
public double X { get; init; }
public double Y { get; init; }
public Point(double x, double y) { X = x; Y = y; }
public override string ToString() => $"({X}, {Y})";
}
3. Demonstrate value equality: Create two Person instances with same data and compare them with ==.with expression: Create a modified copy of a record.init properties: Instantiate struct with object initializer.readonly struct for small, immutable value types to avoid defensive copieswith expression creates a shallow copy with specified changesPerson 1: Person { Name = Alice, Age = 30 }
Person 2: Person { Name = Alice, Age = 30 }
Are equal: True
Person 3 (with): Person { Name = Alice, Age = 31 }
Point: (3, 4)
public record Person(string Name, int Age);public readonly struct Point { ... }var p2 = p1 with { Age = 31 };public double X { get; init; }Review feedback below
abstract record Shape;
record Circle(double Radius) : Shape;
record Rectangle(double Width, double Height) : Shape;
2. Switch expression with type patterns: Calculate area based on shape type.<, >, and, or in patterns._ for default case.and, or, notCircle { Radius: > 5 }_ or exhaustive patternsCircle area: 78.54
Rectangle area: 24
Size of 78.54: Large
Size of 24: Medium
Describe 10: Positive even
Describe -3: Negative
shape switch { Circle c => ..., _ => ... }> 50, > 10 and <= 50Circle { Radius: > 5 }> 0 when n % 2 == 0Review feedback below
#nullable enable directive.string nonNull = "hello"; // Cannot be null
string? maybeNull = null; // Can be null
3. Use null-conditional operator: maybeNull?.LengthmaybeNull ?? "default"maybeNull ??= "assigned"is not null and is null patterns.! (null-forgiving) only when you're certain value is non-nullis not null over != null for pattern matching??= assigns only if current value is nullnonNull length: 5
maybeNull length: (null)
With default: default value
After ??= : now assigned
name is not null: Alice
FindPerson(1): Found Alice
FindPerson(99): Not found
#nullable enable at top of filestring? maybeNull = null;obj?.Propertyvalue ?? "default", value ??= "assign"if (x is not null)Review feedback below