OneOf icon indicating copy to clipboard operation
OneOf copied to clipboard

Pattern matching with OneOfBase reuseable types

Open katy-hughes-cko opened this issue 2 years ago • 1 comments

Hi!

I'm trying to understand how I can use pattern matching with reusable OneOfBase types.

The TResponse generic parameter here is of type PaymentProcessed, but it evaluates response is PaymentResponse paymentResponse as false

In order for this to work I have to continue to use the OneOf<> full type. Thanks for any help!

image

katy-hughes-cko avatar Nov 30 '22 13:11 katy-hughes-cko

@katy-hughes-cko , not sure if I'm missing something, but this works for me:

using OneOf;

PaymentResponse paymentProcessed = new PaymentProcessed();
var result = await DoThingAsync(paymentProcessed);
Console.WriteLine(result);

static async Task<string> DoThingAsync<T>(T response, CancellationToken cancellationToken = default) {
    if (response is PaymentResponse _) {
        return await Task.FromResult("response was a PaymentResponse");
    }

    return await Task.FromResult("Unknown type of response");
}

public class PaymentResponse : OneOfBase<PaymentProcessed, PaymentAccepted, ActionFailed> {
    private PaymentResponse(OneOf<PaymentProcessed, PaymentAccepted, ActionFailed> _) : base(_) { }

    public static implicit operator PaymentResponse(PaymentProcessed _) => new(_);
    public static implicit operator PaymentResponse(PaymentAccepted _) => new(_);
    public static implicit operator PaymentResponse(ActionFailed _) => new(_);

}

public class PaymentProcessed { }

public class PaymentAccepted { }

public class ActionFailed { }

Output:

>  dotnet run
response was a PaymentResponse

jlevier avatar Mar 24 '23 22:03 jlevier