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

Implicit cast from OneOf<> to Task<OneOf<>> #152

Open
amir734jj opened this issue Jul 6, 2023 · 1 comment
Open

Implicit cast from OneOf<> to Task<OneOf<>> #152

amir734jj opened this issue Jul 6, 2023 · 1 comment

Comments

@amir734jj
Copy link

We are using Task<OneOf<>> frequently in our codebase and I wish there was a way to add this implicit cast from OneOf<> to Task<OneOf<>> but we C# doesn't allow adding implicit casts outside of declaring class (i.e. OneOf<>). This is because we have a use case where we use .Switch and in one branch of OneOf we run an async lambda and in the second branch of OneOf we run a sync operation just returning the result. We can use Task.FromResult in the second lambda but I just wish there was a implicit cast from OneOf of anything to Task<OneOf>

public static implicit operator Task<OneOf<T0>>(OneOf<T0> t) => Task.FromResult(t);
@Foxtrek64
Copy link

I disagree that this should be an implicit cast. In my opinion, implicit casts should be reserved for when a particular thing and a particular other thing are synonymous in some manner, and it should always be from more specific to less specific (e.g. a name object which contains first + last may be implicitly cast to string).

I would argue that OneOf<T0> and Task<OneOf<T0>> are not the same - the former is a value container and the latter is the promise of a value container. Additionally, we're moving from less specific to more specific.

If we were to add this, I think my preferred form would either be an explicit operator or, perhaps better, AsTask() or AsValueTask() extensions.

Something like this, either as a member or an extension method.

public Task<OneOf<T0>> AsTask(OneOf<T0> oneOf) => Task.FromResult(oneOf);
public Task<OneOf<T0>> AsTask(Func<OneOf<T0>> factory) => Task.FromResult(factory.Invoke());

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