Is there a way to simulate sum and product types in C#? What I basically want is a common base class and a bunch of marker interfaces for derived classes (sum type). Later I want to use fields of base class type but narrowed down to some subset using the marker interfaces (intersection type).
Here is a Typescript analogy for what I Want to do in C#:
/*... common functionality in base class, doesn't fit interface */
abstract class Token { abstract readonly text: string; }
// marker interfaces, _b and _u added just to simulate nominal type system,
// otherwsie TS would assume Binary === Unary
interface Binary { _b: number }
interface Unary { _u: number }
class PlusToken extends Token implements Unary, Binary { text = "+"; _b = 0; _u = 1; }
class MinusToken extends Token implements Unary, Binary { text = "-"; _b = 0; _u = 1; }
class MulToken extends Token implements Binary { text = "*"; _b = 0; }
class NotToken extends Token implements Unary { text = "!"; _u = 1; }
type BinaryOp = Token & Binary
type UnaryOp = Token & Unary
let validPlus: BinaryOp = new PlusToken();
let validMul: BinaryOp = new MulToken();
let validNot: UnaryOp = new NotToken();
// compiler guards against invalid case
let invalidNot: BinaryOp = new NotToken();
I have dug through the SO and internet already but what I have found so far are generally dated "no" answers. In recent years Java 17 got a bit of a support for that (with sealed records), has C# got any work done?
A follow up question: has there been work on this in C# in recent years or were there any related announcements (for example for algebraic data types support)?