Skip to content

Instantly share code, notes, and snippets.

@manne
Last active January 5, 2020 10:50
Show Gist options
  • Save manne/15fc13d3b09a4fca66ab9496ce67ebdf to your computer and use it in GitHub Desktop.
Save manne/15fc13d3b09a4fca66ab9496ce67ebdf to your computer and use it in GitHub Desktop.
Provides a deconstructor and a method in the "TryGet" style for nullable types in C#.
void Main()
{
Nullable<int> n = 3;
n.HasValue(out var i).Dump();
i.Dump();
var (a, value) = n;
a.Dump();
value.Dump();
n = null;
n.HasValue(out var i2).Dump();
i2.Dump();
}
public static class NullableExtensions
{
public static bool HasValue<T>(this Nullable<T> instance, out T value) where T : struct
{
var result = instance.HasValue;
value = result ? instance.Value : default;
return result;
}
public static void Deconstruct<T>(this Nullable<T> instance, out bool hasValue, out T value) where T : struct
{
hasValue = instance.HasValue;
value = hasValue ? instance.Value : default;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment