Skip to content

Instantly share code, notes, and snippets.

@GaProgMan
Created March 24, 2020 10:49
Show Gist options
  • Save GaProgMan/2f9535264e83e767fad44d8e9267e626 to your computer and use it in GitHub Desktop.
Save GaProgMan/2f9535264e83e767fad44d8e9267e626 to your computer and use it in GitHub Desktop.
Comparing nullables without having to use a .HasValueCheck
using System;
namespace comparingNullables
{
public class Program
{
private int? nullableInt = default;
private int nonNullableInt = 7;
private bool? nullableBool = default;
// default for bools is false, so let's use a value which
// wont be equal to the nullable Value
private bool nonNullableBool = true;
private void ComparingNullableInts()
{
// consider this
if (nullableInt.HasValue && nullableInt.Value == nonNullableInt)
{
Console.WriteLine("They are equal");
}
// vs this
if (Nullable.Equals(nullableInt, nonNullableInt))
{
Console.WriteLine("They are equal");
}
// also consider this
if (nullableInt.HasValue && nullableInt.Value > nonNullableInt)
{
Console.WriteLine($"nameof(nullableInt) is larger than nameof(nonNullableInt)");
}
// vs this
if (Nullable.Compare(nullableInt, nonNullableInt) > 0)
{
Console.WriteLine($"nameof(nullableInt) is larger than nameof(nonNullableInt)");
}
}
private void ComparingNullableEverything()
{
// consider this
if ((nullableInt.HasValue && nullableInt.Value == nonNullableInt) &&
(nullableBool.HasValue && nullableBool == nonNullableBool))
{
Console.WriteLine("Everything is equal");
}
// vs this
if ((Nullable.Equals(nullableBool, nonNullableBool)) &&
(Nullable.Equals(nullableInt, nonNullableInt)))
{
Console.WriteLine("They are equal");
}
}
public void Main(string[] args)
{
ComparingNullableInts();
ComparingNullableEverything();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment