Last active
July 5, 2022 21:38
-
-
Save dimitris-papadimitriou-chr/2f6a34346815c4628b7972e8d8edc871 to your computer and use it in GitHub Desktop.
Minimal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
namespace FunctionalExperimentation.SimpleRefactorings.Medium.FuncTaskCovarinat.Minimal | |
{ | |
public static partial class F | |
{ | |
public static FuncTask<T> ToFuncTask<T>(this Func<Task<T>> @this) => | |
new FuncTask<T>( | |
() => @this().GetAwaiter().GetResult() | |
); | |
public static T GetOrThrowIfFailed<T>(this FuncTask<T> @this, string message) where T : IWithResult | |
{ | |
var value = @this(); // this might also throw exception from Task. | |
return value?.IsSuccesfull ?? false ? value : | |
throw new Exception(message); | |
} | |
} | |
public interface IWithResult | |
{ | |
public bool IsSuccesfull { get; } | |
} | |
public class SomeResult : IWithResult | |
{ | |
public bool IsSuccesfull => true; | |
} | |
public class FuncTaskCovarinat | |
{ | |
public static async Task RunAsync() | |
{ | |
Func<Task<SomeResult>> GetSomethingLazyAsync() => () => Task.FromResult(new SomeResult()); | |
//Func<Task<IWithResult>> t = GetSomethingLazyAsync(); | |
//Error CS0029 Cannot implicitly convert type 'System.Func<System.Threading.Tasks.Task<FunctionalExperimentation.Practical.FuncTaskCovarinat.SomeResult>>' | |
// to 'System.Func<System.Threading.Tasks.Task<FunctionalExperimentation.Practical.FuncTaskCovarinat.IWithResult>>' | |
//ok this is covariant on T | |
FuncTask<IWithResult> lazyResult = GetSomethingLazyAsync().ToFuncTask(); | |
SomeResult result = GetSomethingLazyAsync().ToFuncTask().GetOrThrowIfFailed("failed to get"); | |
} | |
} | |
public delegate T FuncTask<out T>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment