ExhaustiveMatching
ExhaustiveMatching copied to clipboard
Support structurally closed hierarchies like Discriminated Unions
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),
}
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
.
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.
@WalkerCodeRanger Are there chances to get a current build soon published to nuget? Do you have open things to do where I could support?
Is this project still maintained?
@csharper2010 Have you published your version on nuget by any chance?