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 .