Cheat Sheet: Records
Cheat Sheet: Records
A new C# type that is immutable by default. The equality between Records is compared by
structure or by reference.
// Default Record.
public record Person(string Name, int Age);
// Mutable Record.
public record Person(string Name, int Age)
{
public string Name { get; set; } = Name;
public int Age { get; set; } = Age;
}
var person1 = new Person("Bassam Alugili",42 );
var person2 = new Person("Bassam Alugili",42);
Cheat Sheet
Console.WriteLine(ReferenceEquals(person1, person2));
var person3 = person1 with { Age = 43 }; // Change the default record! -->
Create a new one!
Console.WriteLine(person1 == person3); // False; Structural equality.
28.11.2020 Cons:
Allocating a lot of objects.
Pattern Matching Enhancements
C# 9 contains six main changes in pattern matching. Type patterns enhancements and all other patterns are introduced in C# 9.
Type patterns is used to match the input against a type. If the input type is a match to the type specified in the pattern, the match succeeds. C# 9 removes the type pattern followed by
another pattern restriction.
Combinator Patterns Permit the programmer to combine multiple patterns on one line with AND/OR operators or to negate a pattern by using the NOT operator.
- Conjunctive patterns represent the logical “and” of the two sub-patterns pattern1 and pattern2.
- Disjunctive patterns represent the logical “or” of the two sub-patterns pattern1 and pattern2.
- Negated “not” pattern that requires a given pattern not to match.
Parenthesized patterns permit the programmer to put parentheses around any pattern.
Relational patterns permit the programmer to match their input against constant values to determine if the input is > or < or = to that constant.