Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pattern matching with OneOfBase reuseable types #133

Open
katy-hughes-cko opened this issue Nov 30, 2022 · 1 comment
Open

Pattern matching with OneOfBase reuseable types #133

katy-hughes-cko opened this issue Nov 30, 2022 · 1 comment

Comments

@katy-hughes-cko
Copy link

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

@jlevier
Copy link

jlevier commented Mar 24, 2023

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants