Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I see the following code pattern all over the place in my company\'s codebase (.

ID: 642721 • Letter: I

Question

I see the following code pattern all over the place in my company's codebase (.NET 3.5 application):

bool Foo(int barID, out Baz bazObject) {
    try {
            // do stuff
            bazObject = someResponseObject;

            return true;
    }
    catch (Exception ex) {
        // log error
        return false;
    }
}

// calling code
BazObject baz = new BazObject();
fooObject.Foo(barID, out baz);

if (baz != null) {
    // do stuff with baz
}
I'm trying to wrap my head around why you would do this instead of having the Foo method simply take the ID and return a Baz object, instead of returning a value that isn't used and having the actual object be a ref or output parameter.

Is there some hidden benefit of this coding style that I'm missing?

Explanation / Answer

You usually use that pattern so you can write code like this:

if (Foo(barId, out bazObject))
{
//DoStuff with bazobject
}
it's used in the CLR for TryGetValue in the dictionary class for instance. It avoids some redundancy but out and ref parameters always seemed a bit messy to me