Ever since the introduction of LINQ, people have been trying all sorts of clever ways to get more functional constructs into C# to wrap away certain annoying procedural details that are part of the language because of its non-functional beginnings. One of the most annoying class of operations in this context are the TryX methods (e.g.
TryParse and so on) that use
out parameters and force you to break into statements what is otherwise a fluent sequence of calls.
Then there are others, even within LINQ, such as
FirstOrDefault that keeps you from choking like
First does – but then can’t tell the difference between something not being there versus something being there but being null (or the type-default for value types).
I recently stumbled across two instances of the clever things people do, viz. Brad Wilson’s Maybe<T> and JaredPar’s Option<T>. This inspired me to add some more goodness in and cook up something of my own, aptly named Perhaps<T>. I am making it part of the Commons Library, and you can find the source code here:
Here are a few examples of how this might be used:
It’s mostly obvious stuff, but I think this will go a long way in making my code less noisy.