Skip to content

Instantly share code, notes, and snippets.

@GaProgMan GaProgMan/program.cs
Created Mar 24, 2020

Embed
What would you like to do?
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
You can’t perform that action at this time.