Search code examples
c#validationif-statementcomparison

Most efficient way to check three objects for not being null OR only two of them can be null


I am struggling with a problem of validating three objects (A, B, C)

These are my conditions

  • none of then can be null
  • at most one of then can be not null

I want to resolve it without many if expression and creating monstrous code.

So

  A  B  C
A 1  0  0
B 0  1  0
C 0  0  1

as it show I need to achieve something like this pseudo table before only one of them can be true and all the other are false

Final

what expression can provide such validation?


Solution

  • Create a helper method to do it (with tests), then at that point, have the code as messy or as clean as you wish in order to achieve your targets.

    This is a fairly simple implementation; guarantees exactly 3 checks every time.

    public static bool OnlyOneNotNull(object object1, object object2, object object3)
    {
        if (object1 != null)
            return object2 == null && object3 == null;
    
        if (object2 != null)
            return object3 == null;
    
        return object3 != null;
    }
    

    Usage is simply:

    if (OnlyOneNotNull(A, B, C))
    {
        //do something
    }