0Pricing
C# Academy · Lesson

Domain modeling with discriminated unions (records) — C# 6 emulation

Model a discriminated union in C# 6 using a tag enum and small classes, create factory methods, and handle variants via switch with a default throw.

DU idea in C# 6

Aim: Build a small discriminated union in C# 6.

  • Tag enum for the active case
  • Small case classes for data
  • Factory methods to create valid cases
  • Switch + default throw to handle all variants

Tag + factories

Use a tag enum and factory methods to construct only valid cases; fields for other cases stay unused.

using System;

public enum PaymentKind { Cash, Card, Wire }

public sealed class Payment
{
  public PaymentKind Kind;

  // per-case data (only one is meaningful per instance)
  public string CardLast4; // for Card
  public string Iban;      // for Wire

  private Payment() { }

  // factories keep invariants
  public static Payment Cash()
  {
    Payment p = new Payment();
    p.Kind = PaymentKind.Cash;
    return p;
  }

  public static Payment Card(string last4)
  {
    if (string.IsNullOrEmpty(last4) || last4.Length != 4)
      throw new ArgumentException("last4 must be 4 digits", "last4");
    Payment p = new Payment();
    p.Kind = PaymentKind.Card;
    p.CardLast4 = last4;
    return p;
  }

  public static Payment Wire(string iban)
  {
    if (string.IsNullOrEmpty(iban))
      throw new ArgumentException("iban must not be empty", "iban");
    Payment p = new Payment();
    p.Kind = PaymentKind.Wire;
    p.Iban = iban;
    return p;
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    Payment a = Payment.Cash();
    Payment b = Payment.Card("1234");
    Payment c = Payment.Wire("TR00BANKIBAN");
    Console.WriteLine(a.Kind + ", " + b.Kind + ", " + c.Kind);
  }
}

All lessons in this course

  1. is patterns; relational & logical patterns (C# 6 emulation)
  2. switch expressions; exhaustive checks with when (C# 6 emulation)
  3. Domain modeling with discriminated unions (records) — C# 6 emulation
← Back to C# Academy