MadsKirkFoged / EngineeringUnits

Working with units made easy with automatic unit-check and converting between units
MIT License
41 stars 10 forks source link

Null comparison with operator throws NullReferenceException #31

Closed JFReni closed 8 months ago

JFReni commented 1 year ago
Temperature? temperature = GetTemperatureFromMethodThatCouldReturnNull();

if(temperature == null)
{
   ...
}

The null comparison in the if statement throws because it uses the overloaded == operator for BaseUnit vs BaseUnit which calls:

if (left.Unit != right.Unit)

When right is null such as the comparison above this throws a NullReferenceException.

MadsKirkFoged commented 1 year ago

Hi JFReni

Thank you for reporting this bug! I have fixed it however it is not recommended in C# to use == as nullcheck. Instead use the is null or is not null

Temperature temperature2 = null;

//Not recommended!
if (temperature2 == null)
{                
}

//Recommended!
if (temperature2 is null)
{
}

//Recommended!
if (temperature2 is not null)
{
}