Skip to content

Instantly share code, notes, and snippets.

@nickalbrecht
Created March 18, 2025 00:02
Show Gist options
  • Save nickalbrecht/f0078ae1401326f579997bd16dc05fca to your computer and use it in GitHub Desktop.
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 …
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