I need to do a comparaison between an object and NULL. When the object is not NULL I fill it with some data.
Here is the code :
if (region != null)
Both of the overloads are incorrect
public static bool operator ==(Region r1, Region r2)
{
if (object.ReferenceEquals(r1, null))
{
return false;
}
if (object.ReferenceEquals(r2, null))
{
return false;
}
return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);
}
if r1 And r2 are null, the first test (object.ReferenceEquals(r1, null)) will return false, even though r2 is also null.
try
//ifs expanded a bit for readability
public static bool operator ==(Region r1, Region r2)
{
if( (object)r1 == null && (object)r2 == null)
{
return true;
}
if( (object)r1 == null || (object)r2 == null)
{
return false;
}
//btw - a quick shortcut here is also object.ReferenceEquals(r1, r2)
return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);
}
This can sometimes happen when you have multiple threads working with the same data. If this is the case, you can use a lock to prevent them from messing with eachother.