Home > Back-end >  C# checking for Null when a class has operator overloads
C# checking for Null when a class has operator overloads

Time:06-10

My .NET Framework v4.5.2 app is throwing a NullReferenceException on the following line:

if (CurrentZip.Container.Exists)

I want to write a check around this to make sure that CurrentZip.Container is not null, however there are existing operator overloads for the type of Container which is called RichFileInfo (not written by me):

    public static bool operator ==(RichFileInfo x, RichFileInfo y)
    {
        return String.Equals(x.FullName, y.FullName, StringComparison.OrdinalIgnoreCase);
    }

    public static bool operator !=(RichFileInfo x, RichFileInfo y)
    {
        return !String.Equals(x.FullName, y.FullName, StringComparison.OrdinalIgnoreCase);
    }

So, even checking CurrentZip.Container != null will throw a NullReferenceException.

How do I safely check for null in this case of there being an operator overload?

CodePudding user response:

Object.ReferenceEquals(objectA, objectB) should accomplish what you need (if the other answer didn't already solve your issue). It can't be overridden so it should always work the same, and evaluates to a bool so it can be used in the same manner as your other checks.

See Microsoft's documentation on it here.

To be clear, you would want to implement it like so to compare against null:

//invert
if(!Object.ReferenceEquals(CurrentZip.Container, null)) 
{
    // is not equal to null
    
}

CodePudding user response:

maybe just do if(CurrentZip.Container is null && CurrentZip.Container.Exists)?

here's from the Microsoft docs:

When you match an expression (is) against null, the compiler guarantees that no user-overloaded == or != operator is invoked. Beginning with C# 11, you can use is null on unconstrained generic types. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/is

  •  Tags:  
  • c#
  • Related