I often use the TryDoSomething
pattern like this totally made up example:
GameContext gameContext;
if (gamesRepository.TryLoadLastGame(out gameContext))
{
// Perform actions with gameContext instance.
}
else
{
// Create a new game or go to home screen or whatever.
}
This allows a nice readable flow but it also allows a success status true
but a null return value which is useful sometimes for communicating "I was able to get you your thing but its actually null".
With async-await, the asynchronous lower APIs "force" calling APIs to do the right thing and work asynchronously. However, without out
parameters, this pattern doesn't work.
How can it be achieved?
I have an answer, and am answering Q/A style to see how other people think about it.
For comparison purposes, here's a similar approach that I employ:
So far I've used a little class called
Attempt<T>
:Which is used within a Try method like this:
And is consumed like so:
Or, ignoring errors.