discriminated union in csharp

In C#, a discriminated union is created using the switch statement with pattern matching. It allows defining a type that can hold one of several specified types, with a tag that indicates which one is held.

Here is an example:

main.cs
public class UnionExample
{
    public enum ShapeType { Square, Circle, Rectangle };

    public class Shape
    {
        public ShapeType Type { get; }
        public Shape(ShapeType type) => Type = type;
    }
    public class Square : Shape
    {
        public int SideLength { get; }
        public Square(int sideLength) : base(ShapeType.Square) => SideLength = sideLength;
    }

    public class Circle : Shape
    {
        public int Radius { get; }
        public Circle(int radius) : base(ShapeType.Circle) => Radius = radius;
    }

    public class Rectangle : Shape
    {
        public int Width { get; }
        public int Height { get; }
        public Rectangle(int width, int height) : base(ShapeType.Rectangle)
        {
            Width = width;
            Height = height;
        }
    }

    public static void Main()
    {
        Shape[] shapes = new Shape[] { new Square(5), new Circle(3), new Rectangle(4, 6) };

        foreach(var shape in shapes) {
            switch(shape) {
                case Square square:
                    Console.WriteLine($"Square with side length {square.SideLength}");
                    break;
                case Circle circle:
                    Console.WriteLine($"Circle with radius {circle.Radius}");
                    break;
                case Rectangle rectangle:
                    Console.WriteLine($"Rectangle with width {rectangle.Width} and height {rectangle.Height}");
                    break;
            }
        }
    }
}
1516 chars
52 lines

In this example, we define a base class Shape and several derived classes Square, Circle, and Rectangle. We use an enum ShapeType to tag each shape with a type. Then we define an array of shapes and loop through them, using a switch statement with pattern matching to handle each shape based on its type. Depending on the type of shape, we can access its properties and print out information about it.

gistlibby LogSnag