Call a function and test it's return against null/failure at the same time?

So I have a function that does some validation. Let’s use this as an example:

int product = x * y;
if(product >= 20)
return product;
return 0;
}

If x times y is >= 20, then return the product, otherwise return 0, a failure condition.

In other languages I’ve been able to do something like (pseudocode, clearly):

log("It failed");
} else {
log("It worked, the answer is" + result);
}

I was able to run the function and store the result inside the if statement, and then test that result at the same time. Is this possible in C#/Unity? I’ve tried using a few different formats and none seem to work. Up til now I’ve been doing:

if(result == 0) {
log("It failed");
} else {
log("It worked, the answer is" + result);
}

Yes, it’s just an extra line of code, but for what I’m used to writing and for the sake of brevity, I prefer having tests like that in a simple single line assign-and-test format, if possible.

If not, no big deal. Just looking to remove some extra lines of code.

Thanks

you need to make the “testFunc” function a bool, and then yes you can do that :slight_smile:

Something like (pseudo, may not work and I am on a train on mobile so typed without any coding app):

public bool testFunc(int x, int y, out int productOut) {

    int product = x * y;

    if(product >= 20)
{
productOut = product;
        return true;
}

productOut  = 0;
    return false;

}

This requires you to pass in the productOut variable which will contain the int it returns out (as its actual return type is a bool, which allows you to use it in statements as you require)

It also requires you to write your logic statements using the function differently. But using it as a bool will allow you to do logic with it while using an out variable allows to still get out a “return” int

This is a nice well-established pattern in C#. Many things in the C# API (like the int.TryParse() family of calls) and also things in the Unity API (like Physics.Raycast( Ray, RaycastHit); all use this pattern.

3 Likes