A generic record in C# is a data-centric type that combines the value-based equality and non-destructive mutation semantics of records with the type safety of generics. It allows the definition of a record blueprint where one or more property types are deferred until instantiation via type parameters.Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
Syntax and Declaration
Generic records support both positional and nominal declaration styles. Type parameters are declared immediately following the record identifier.Type Constraints
Standard generic type constraints (where clauses) apply to generic records. In positional syntax, the constraint is placed after the primary constructor parameters.
Compiler-Synthesized Members
When the C# compiler generates a generic record, it synthesizes several members adapted to the type parameterT:
- Value Equality (
Equalsand==): The compiler implementsIEquatable<TRecord>. For generic properties, it utilizesEqualityComparer<T>.Default.Equals()to ensure correct equality checks regardless of whetherTresolves to a reference type or a value type. - Hashing (
GetHashCode): The synthesized hash code incorporates the generic properties usingEqualityComparer<T>.Default.GetHashCode(). - Deconstruction: For positional generic records, the compiler generates a
Deconstructmethod matching the generic signature of the primary constructor. - Formatting (
PrintMembers): The compiler generates aPrintMembersmethod that callsToString()on the generic properties to support built-in record string formatting.
Non-Destructive Mutation (with Expressions)
Generic records fully support with expressions. The compiler synthesizes a hidden copy constructor that accepts an instance of the generic record. The resulting type of a with expression retains the exact constructed type of the original instance.
Inheritance Rules
Generic records follow strict inheritance rules specific to the record type system:- A
record classcan only inherit from anotherrecord class(orobject). - A generic record can inherit from a non-generic record, provided it supplies the required base constructor arguments.
- A generic record can inherit from another generic record, passing its type parameters up the inheritance chain.
Covariance and Contravariance
Because generic records are classes or structs (not interfaces or delegates), their type parameters cannot be declared as covariant (out) or contravariant (in). A Wrapper<string> cannot be implicitly cast to a Wrapper<object>, even though string derives from object. Type parameters in generic records are strictly invariant.
Master C# with Deep Grasping Methodology!Learn More





