Playing around with the record type in C#, it looks like it could be quite useful to build discriminated-union-like data structures, and I'm just wondering if I'm missing some gotchas that I'll regret later. For example:
abstract record CardType{
    // Case types
    public record MaleCardType(int age) : CardType{}
    public record FemaleCardType : CardType{}
    // Api
    public static MaleCardType Male(int age) => new MaleCardType(age);
    public static FemaleCardType Female => new FemaleCardType();
}
var w = CardType.Male(42);
var x = CardType.Male(42);
var y = CardType.Male(43);
var z = CardType.Female;
Assert.Equal<CardType>(w,x); //true
Assert.Equal<CardType>(x,y); //false
Assert.Equal<CardType>(y,z); //false
It seems to be a lot simpler than building abstract classes with singletons and equality comparers and all that, but am I missing some reason why I wouldn't want to do this?
It's a great way to go, I've been playing around with it, for instance, on https://fsharpforfunandprofit.com/posts/designing-for-correctness/ which has some examples of C# code, some F# code that uses types and discriminated unions, and then some modified (but still terrible C# code). So I rewrite the C# using C# 9s records and the same way of doing DUs
Sample code, which is a tiny bit uglier than the F#, but still quite concise and has the advantages of the F# code .
using System;
using System.Collections.Immutable;
namespace ConsoleDU
{
    record CartItem(string Value);
    record Payment(decimal Amount);
    abstract record Cart
    {
        public record Empty () : Cart
        {
            public new static Active Add(CartItem item) => new(ImmutableList.Create(item));
        }
        public record Active (ImmutableList<CartItem> UnpaidItems) : Cart
        {
            public new Active Add(CartItem item) => this with {UnpaidItems = UnpaidItems.Add(item)};
            public new Cart Remove(CartItem item) => this with {UnpaidItems = UnpaidItems.Remove(item)} switch
            {
                var (items) when items.IsEmpty => new Empty(),
                { } active => active
            };
            public new Cart Pay(decimal amount) => new PaidFor(UnpaidItems, new(amount));
        }
        public record PaidFor (ImmutableList<CartItem> PaidItems, Payment Payment) : Cart;
        public Cart Display()
        {
            Console.WriteLine(this switch
            {
                Empty => "Cart is Empty",
                Active cart => $"Cart has {cart.UnpaidItems.Count} items",
                PaidFor(var items, var payment) => $"Cart has {items.Count} paid items. Amount paid: {payment.Amount}",
                _ => "Unknown"
            });
            return this;
        }
        public Cart Add(CartItem item) => this switch
        {
            Empty => Empty.Add(item),
            Active state => state.Add(item),
            _ => this
        };
        public static Cart NewCart => new Empty();
        public Cart Remove(CartItem item) => this switch
        {
            Active state => state.Remove(item),
            _ => this
        };
        public Cart Pay(decimal amount) => this switch
        {
            Active cart => cart.Pay(amount),
            _ => this
        };
    }
    class Program
    {
        static void Main(string[] args)
        {
            Cart.NewCart
                .Display()
                .Add(new("apple"))
                .Add(new("orange"))
                .Display()
                .Remove(new("orange"))
                .Display()
                .Remove(new("apple"))
                .Display()
                .Add(new("orange"))
                .Pay(23M)
                .Display();
            ;
        }
    }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With