4 04 2014
I’ve blogged about this subject before, but I REALLY hate null refs. This is one of the reasons I love F# and other functional languages, null ref’s almost never happen. But, in the real world I work as a C# dev and have to live with C#’s… nuisances.
In the other post, a big problem with the dynamic proxy was that it only worked with virtual methods, so it wasn’t really all that practical. This time around I decided to try a different route and leverage expression tree’s to actually build out the if checks automatically.
For the impatient, full source available at my github and the library is available on nuget
Let me demonstrate the final usage first. If all of users properties and methods return null, executing this whole chain would fail starting at the null result of
GetSchool(). But, by using the Option static … Read more
20 05 2013
In a production application you frequently can find yourself working with objects that have a large accessor chain like
But when you want to program defensively you need to always do null checks on any reference type. So your accessing chain looks more like this instead
if (student.School != null)
if (student.School.District != null)
if (student.School.District.Street != null)
s += student.School.District.Street.Name;
Which sucks. Especially since its easy to forget to add a null check, and not to mention it clutters the code up. Even if you used an option type, you still have to check if it’s something or if its nothing, and dealing with huge option chains is just as annoying.
One solution is to use the maybe monad, which can be implemented using extension methods and lambdas. While this is certainly better, it can still can get unwieldy.
What I … Read more