Skip to content

Support structurally closed hierarchies like Discriminated Unions #42

@csharper2010

Description

@csharper2010

It would be helpful to detect the closed hierarchy of a class with private constructor and nested subclasses having either also a private constructor or a sealed modifier. This is a way to simulate the desparately missing discriminated unions safely in C#.

public abstract class Result<TSuccess, TError> {
    private Result() { }

    public sealed class Success : Result<TSuccess, TError> {
        public TSuccess Value { get; }
        public Success(TSuccess value) { Value = value; }
    }

    public sealed class Error : Result<TSuccess, TError> {
        public TError Value { get; }
        public Error(TError value) { Value = value; }
    }
}

A switch expression like this should provide the error:

var x = result switch
{
    Result<string, string>.Error error => ""Error: "" + error,
    _ => throw ExhaustiveMatch.Failed(result),
};

This would be o.k.:

var x = result ◊1switch{
    Result<string, string>.Error error => ""Error: "" + error,
    Result<string, string>.Success success => ""Success: "" + success,
    _ => throw ExhaustiveMatch.Failed(result),
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions