Skip to content

Instantly share code, notes, and snippets.

@JimBobSquarePants
Created January 14, 2023 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JimBobSquarePants/e6a8370c7f7784fd792cf99b3e37020b to your computer and use it in GitHub Desktop.
Save JimBobSquarePants/e6a8370c7f7784fd792cf99b3e37020b to your computer and use it in GitHub Desktop.
A nullable aware Attempt type for wrapping nullable async responses.
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// A wrapper for nullable values that correctly handles the return type based on the result.
/// </summary>
/// <typeparam name="T">The type of nullable value.</typeparam>
public readonly struct Attempt<T>
{
/// <summary>
/// Gets a value indicating whether the attempted return was successful.
/// </summary>
[MemberNotNullWhen(returnValue: true, member: nameof(Value))]
public bool Success => this.Value is not null;
/// <summary>
/// Gets the value when the attempted return is successful; otherwise, the default value for the type.
/// </summary>
public T? Value { get; init; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment