Record
A record is an immutable datatype that contains a collection of named fields.
It should be directly compared to a structure -Structureand used when you need immutability.
The fields of a record must be a record datatype themselves.
A record is a Type. You can declare a new instance of it and such can have local defined constructors - Constructor
Declaration
To declare a new record define a top level construct using the keyword record followed by the desired Identifier. The name must be unique within the corresponding namespace - Namespace
A structure contains any number of named Fields - Field All fields must be record datatypes. They are immutable and cannot have their value changed after execution of the constructor. They can also be initialized to initial values.
//Physically located in Records
record CSharpBoundFields
{
int A;
double B = -0.07;
bool C = false;
}
structure IAmNotARecord
{
int HonkHonk;
}
record ExampleRecord
{
string Name = "Bobby Buckets";
CSharpBoundFields MahFields;
IAmNotARecord FailHard;//This line causes a compile error
this ExampleRecord(int b)
{
MahFields.B = b;
}
}Remarks
Shift records are similiar to C# records but with the addition guarentee of only containing other records with init setters.
A record can only inherit from other records.
All C# primitives are exposed as records in Shift
C# Equivalent
All fields in a Shift record are like init only properties in a C# record. Furthermore the compiler enforces that any Type used as a property conforms to the same constraints.
public record CSharpBoundFields
{
public int A { get; init set; } = new int();
public double B { get; init set; } = new double();
public bool C { get; init set; } = new bool();
}
public record ExampleRecord
{
public string Name { get; init set; } = "Bobby Buckets";
public CSharpBoundFields MahFields { get; init set; } = new CSharpBoundFields();
public ExampleRecord(int b)
{
MahFields.B = b;
}
}Usage
All of a record's fields can be accessed when you have an instance of a type. Records are a immutable datatype so their fields cannot be assigned a new value at runtime.
var boundFields = new CSharpBoundFields{ B = 7.3848, C = true };
boundFields.A = 3;//Compile error because CSharpBoundFields is a record type
var example = new ExampleRecord();//Default constructors always existC#'s with syntax is supported in Shift to allow non-destructible mutation of records.
//Using the code from the above example
var safeRecordMutation = boundFields with { A = 3 };It's important to note that a record within a structure is still immutable. Nothing about nesting them in structures change how they behave.