Last active
January 5, 2020 10:50
-
-
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#.
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
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