Last active
May 16, 2020 14:51
-
-
Save plioi/274a94fd6541556adbb646f8411dc925 to your computer and use it in GitHub Desktop.
Shorthand for the int.TryParse(string, out int value) pattern, useful when the C# 8 "Nullable Reference Types" feature is enabled.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics.CodeAnalysis; | |
public static class Maybe | |
{ | |
public static bool Try<T>(Func<T> maybeGetValue, [NotNullWhen(true)] out T output) | |
{ | |
output = maybeGetValue(); | |
return output != null; | |
} | |
public static bool Try<TInput, TOutput>(Func<TInput, TOutput> maybeGetValue, TInput input, [NotNullWhen(true)] out TOutput output) | |
{ | |
output = maybeGetValue(input); | |
return output != null; | |
} | |
} | |
//Usage: | |
using static Maybe; | |
using static System.Environment; | |
... | |
if (Try(GetEnvironmentVariable, variable, out value)) | |
{ | |
//GetEnvironmentVariable(variable) returned a non-null value. | |
//The compiler knows that `value` is not null in this block. | |
} | |
else | |
{ | |
//GetEnvironmentVariable(variable) returned a null value. | |
//The compiler knows to warn about possibly-null `value` in this block. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment