Skip to content

Commit

Permalink
Fix for Broken (Value)Task.Cast<>
Browse files Browse the repository at this point in the history
  • Loading branch information
louthy committed Nov 16, 2022
1 parent c124a20 commit b86d98e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 23 deletions.
17 changes: 8 additions & 9 deletions LanguageExt.Core/Concurrency/Task/Task.Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -279,19 +279,18 @@ public static async Task<Unit> Iter<T>(this Task<T> self, Action<T> f)
public static Task<A> PlusFirst<A>(this Task<A> ma, Task<A> mb) =>
default(MTaskFirst<A>).Plus(ma, mb);

class PropCache<T>
{
public static PropertyInfo Info = typeof(T).GetTypeInfo().DeclaredProperties.Where(p => p.Name == "Result").FirstOrDefault();
}

public static async Task<A> Cast<A>(this Task source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
await source.ConfigureAwait(false);
var prop = PropCache<A>.Info;
return prop != null
? (A) prop.GetValue(source)
: default(A);

return source.GetType() switch
{
var taskTy when taskTy.IsGenericType &&
taskTy.GenericTypeArguments.Length == 1 &&
taskTy.GenericTypeArguments[0] == typeof(A) => (A)((dynamic)source).Result,

This comment has been minimized.

Copy link
@tomachristian

tomachristian Nov 16, 2022

@louthy it would have been more correct to check if taskTy.GenericTypeArguments[0] IsAssignableTo typeof(A).

_ => default!

This comment has been minimized.

Copy link
@tomachristian

tomachristian Nov 16, 2022

In this case it would act more as an As<T> rather than a cast. Based on how C# deals with casts, this should have "thrown"/errored in some way.

};
}

public static async Task<Unit> ToUnit(this Task source)
Expand Down
20 changes: 6 additions & 14 deletions LanguageExt.Core/Concurrency/ValueTask/ValueTask.Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -278,20 +278,12 @@ public static async ValueTask<Unit> Iter<T>(this ValueTask<T> self, Action<T> f)
[Pure]
public static ValueTask<A> Plus<A>(this ValueTask<A> ma, ValueTask<A> mb) =>
default(MValueTask<A>).Plus(ma, mb);

class PropCache<T>
{
public static PropertyInfo Info = typeof(T).GetTypeInfo().DeclaredProperties.Where(p => p.Name == "Result").FirstOrDefault();
}

public static async ValueTask<A> Cast<A>(this ValueTask source)
{
await source.ConfigureAwait(false);
var prop = PropCache<A>.Info;
return prop != null
? (A) prop.GetValue(source)
: default(A);
}

/// <summary>
/// Cast a ValueTask to a ValueTask<A> (may throw if underlying value doesn't exist)
/// </summary>
public static ValueTask<A> Cast<A>(this ValueTask source) =>
new(source.AsTask().Cast<A>());

public static async ValueTask<Unit> ToUnit(this ValueTask source)
{
Expand Down

0 comments on commit b86d98e

Please sign in to comment.