Skip to content

Commit

Permalink
Removed type cast for each call
Browse files Browse the repository at this point in the history
  • Loading branch information
sakno committed Mar 20, 2024
1 parent c1e9b57 commit 95c7758
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/DotNext/Func.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,15 @@ public static Func<T> Constant<T>(T obj)
// slow path - allocates a new delegate
return obj is null
? Default!
: obj.UnboxAny<T>;
: typeof(T).IsValueType
? new BoxedConstant<T>() { Value = obj }.GetValue
: Unsafe.As<T, object>(ref obj).UnboxRefType<T>;

static T? Default() => default;
}

private static T UnboxAny<T>(this object obj) => (T)obj;
private static T UnboxRefType<T>(this object obj)
=> Unsafe.As<object, T>(ref obj);

private static Func<bool> Constant(bool value)
{
Expand Down Expand Up @@ -481,4 +484,11 @@ public static Result<TResult> TryInvoke<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10,

return result;
}

private sealed class BoxedConstant<T> : StrongBox<T>
{
internal T GetValue() => Value!;

public override string? ToString() => Value?.ToString();
}
}

0 comments on commit 95c7758

Please sign in to comment.