Details

Ensure Method Always Returns NotNull

Isn't it tiring always having to check for null from a method you are certain never returns null?

Say no more.

Create a static class to enforce the constraint

public static class Constraint
{
   public static void NotNull([NotNull] object? o, string message = "Value cannot be null.")
   {
       if (o is null)
       {
           throw new InvalidOperationException(message);
       }
   }
}

And then call it whenever you want like a king

[return: NotNull]
public string GetUserEmail()
{
   var email = _httpContextAccessor?.HttpContext
       ?.User.FindFirst(ClaimTypes.Email)?.Value;
       
   Constraint.NotNull(email, "User is unauthenticated or email is missing.");
   
   return email;
}

PS: You can even use it without the [return: NotNull] annotation.