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

Moving extension methods onto IResult (to enable covariance) #530

Open
redx177 opened this issue Feb 21, 2024 · 1 comment
Open

Moving extension methods onto IResult (to enable covariance) #530

redx177 opened this issue Feb 21, 2024 · 1 comment

Comments

@redx177
Copy link

redx177 commented Feb 21, 2024

Covariance is only working with interfaces. Meaning something like this is possible:

public interface IVehicle { }
public class Car : IVehicle { }
public class Bus : IVehicle { }

IResult<IVehicle> carResult1 = Result.Success(new Car());

This on the other hand is not possible:

Result<IVehicle> carResult2 = Result.Success(new Car());

The solution seams simple, just go with IResult rather than Result.
But all the extension methods (those) are on Result, and not on IResult.

Is there a possibility to put all extension methods onto IResult rather than Result?
The "creation" methods (those) can stay on Result, but they return an IResult.

I guess when the extension methods are moved to IResult, we break compatibility...
If the extension methods are copied to IResult, the codebase gets much bigger...

@redx177 redx177 changed the title Moving extension methods on IResult (to enable covariance) Moving extension methods onto IResult (to enable covariance) Feb 21, 2024
@hankovich
Copy link
Collaborator

Yes, it's one of the C# limitations. The solution here will be to specify type explicitely like

var carResult2 = Result.Success<IVehicle>(new Car());

The problem I see with the extensions to IResult are

  1. Async extensions. Tasks/ValueTasks are not delegates and interfaces, so Task<Result<int>> with not be suitable for extensions accepting Task<IResult<T>>, only to extensions accepting Task<Result<T>>. The possible solution is to parameterize extensions to accept Task<TResult<TValue>> where TResult : IResult<TValue>, but C# will not infer type parameters, so everyone will have to provide them explicitely
  2. IResult is an interface, so there will be a lot of unnecessary allocations

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