record: C# like records for D

Dylan Graham dylan.graham2000 at gmail.com
Wed Jul 14 23:16:05 UTC 2021


[DUB](https://code.dlang.org/packages/record)
[Github](https://github.com/hmmdyl/record)

This is record. It aims to implement records similar to what C# 
has by leveraging D's metaprogramming. [C# Example 
1](https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/types/records) [C# Example 2](https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/records).

Future steps are going to be adding a record struct; default 
value support; init-only-setters like in C#, wherein at the end 
of construction or duplication, the init lambda for the field is 
called, and the field can be set that once.

Example:

```D
import drecord;

alias MyRecord = record!(
     get!(int, "x"), /// x is an int, can only be set during 
construction
     get_set!(float, "y"), /// y is a float, can be get or set 
whenever
     property!("getDoubleOfX", (r) => r.x * 2), /// a property 
that returns the double of x
     property!("getMultipleOfX", (r, m) => r.x * m, int), /// that 
takes an argument and multiples x by that value
     property!("printY", (r) => writeln(r.y)), /// prints y
     property!("resetY", (r) => r.y = 0) /// resets y to 0f
);

auto r = new MyRecord(12, 4.5f); /// sets x, y

writeln(r); // { x = 12, y = 4.5f }
writeln(r.toHash); // 376

writeln(r.x); // 12
writeln(r.getDoubleOfX); // 24
writeln(r.getMultipleOfX(4)); // 48
r.printY; // 4.5
r.resetY;
writeln(r.y); // 0
r.y = 13f;
r.printY; // 13

/// Duplicate r, and set x to 17 (we can only do this in ctor, or 
during duplication)
/// This is equivalent to C#'s "with" syntax for records
auto q = r.duplicate!("x")(17);
writeln(q); // {x = 17, y = 0}
writeln(q == r); // false
writeln(q is r); // false

auto b = r.duplicate; // duplicate, don't change any fields
writeln(b == r); // true
writeln(b is r); // false
```


More information about the Digitalmars-d-announce mailing list