Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dimitris-papadimitriou-chr/9cd3403d42ce1ef6da593d0be5fc0cdc to your computer and use it in GitHub Desktop.
Save dimitris-papadimitriou-chr/9cd3403d42ce1ef6da593d0be5fc0cdc to your computer and use it in GitHub Desktop.
using System;
using System.Threading.Tasks;
namespace FunctionalExperimentation.FuncTaskCovarinat.Minimal.DelegateAdapter
{
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 GetOrThrowIfNull<T>(this FuncTask<T> @this, string message)
{
var value = @this(); // this might also throw exception from Task.
return 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()
.GetOrThrowIfNull("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