C# 6 Null Propagation Implemention in C# 5?
- Posted in:
- C#
I was answering SO questions and someone asked how to null guard stuffs when calling a property or a method of something that might be null.
I mentioned that C# 6 provides a way to do this by allowing you to use the following syntax: foo?.bar?.baz
which will prevent the code from parsing the rest and erroring out once a null is encounter anywhere in the method / property chain which it is called null-propagation.
So, an idea popped in my mind since C# 6 is not quite there yet, how can we do this in C# 5? After some thinking, I came up with the idea of using lambda expression combined with extension method and some generic magic that I think might work and came up with the following syntax: foo._(_=>_.bar)._(_=>_.baz)
that seems to work okay.
The implementation is like so:
public static class ObjectExtension { //Probably not a good idea to name your method _, but it's the shortest one I can find, I wish it could be _?, but can't :( public static K _<T, K>(this T o, Func<T, K> f) { try { var z = f(o); return z; } catch(NullReferenceException nex) { Trace.TraceError(nex.ToString()); return default(K); } } }
The running example can be found below: