Skip to content

Instantly share code, notes, and snippets.

@plioi
Last active May 16, 2020 14:51
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 plioi/274a94fd6541556adbb646f8411dc925 to your computer and use it in GitHub Desktop.
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.
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