Created
March 18, 2025 00:02
-
-
Save nickalbrecht/f0078ae1401326f579997bd16dc05fca to your computer and use it in GitHub Desktop.
Generic extension method to check if any variable backed by a nullable value type is `null`, or whatever their default value is. I use it for dealing with `Guid?` but it would work with any value type such as `int?` to combine checks of it it's null or holds the default value for that type. `NotNullWhen` is for when the project has the Nullable …
This file contains hidden or 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
public static partial class ExtensionMethods | |
{ | |
public static bool IsNullOrDefault<T>([NotNullWhen(false)] this T? value) where T : struct | |
{ | |
//return value == null || value.Equals(default(T)); Simpler, but my research online recommended using EqualityComparer<T>.Default instead of value.Equals | |
return !value.HasValue || EqualityComparer<T>.Default.Equals(value.Value, default); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment