ExhaustiveMatching icon indicating copy to clipboard operation
ExhaustiveMatching copied to clipboard

Support structurally closed hierarchies like Discriminated Unions

Open csharper2010 opened this issue 2 years ago • 5 comments

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 ◊1⟦switch⟧
{
    Result<string, string>.Error error => ""Error: "" + error,
    Result<string, string>.Success success => ""Success: "" + success,
    _ => throw ExhaustiveMatch.Failed(result),
}

csharper2010 avatar Apr 04 '22 14:04 csharper2010

A similar case applies even when the subclasses are not nested classes, but all the constructors of the base class are private or private protected.

WalkerCodeRanger avatar May 16 '22 05:05 WalkerCodeRanger

Yes, i did not consider private protected... could add that in another step.

So if there is at least one private protected constructor and all constructors are private or private protected and all subclasses (recursively) in the compilation unit are either sealed or also have at most private protected visibility in constructor, the hierarchy is also known to be structurally closed.

csharper2010 avatar May 17 '22 06:05 csharper2010

@WalkerCodeRanger Are there chances to get a current build soon published to nuget? Do you have open things to do where I could support?

csharper2010 avatar Oct 07 '22 10:10 csharper2010

Is this project still maintained?

chtenb avatar Jun 12 '23 14:06 chtenb

@csharper2010 Have you published your version on nuget by any chance?

chtenb avatar Jun 13 '23 11:06 chtenb