The way to reduce / exclude cascading null checks in an if-statement

I have this condition

if(Model.Bids != null && Model.Bids.Items != null && Model.Bids.Items.Count > 0) { ... } 

The problem is that I find it ugly. I could write a function that encapsulates this, but I wonder if there is anything else that will help me write something like just the important bits below without doing null checks. If not, it will be a convenient extension of the language.

 if(Model.Bids.Items.Count > 0) { ... } 
+3
coding-style
source share
1 answer

For C #, these two options achieve what you want, but I would not put this into my software quickly. I also doubt that this is becoming more readable or more understandable. There is another option, but this requires reorganizing the model class chain. If you implement NullObject for the Bids type and the Item type, you can do if(Model.Bids.Items.Count > 0) because all types will not be null, but has an implementation that handles an empty state (like String.Empty)

assistants

 /* take a func, wrap in a try/catch, invoke compare */ bool tc(Func<bool> comp ) { try { return comp.Invoke(); } catch (Exception) { return false; } } /* helper for f */ T1 f1<T,T1>(T root, Func<T, T1> p1) where T:class { T1 res = default(T1); if (root != null) { res = p1.Invoke(root); } return res; } /* take a chain of funcs and a comp if the last in the chain is still not null call comp (expand if needed) */ bool f<T,T1,T2,TL>( T root, Func<T,T1> p1, Func<T1,T2> p2, Func<T2,TL> plast, Func<TL, bool> comp) where T:class where T1:class where T2:class { var allbutLast = f1(f1(root, p1), p2); return allbutLast != null && comp(plast.Invoke(allbutLast)); } 

Using

 var m = new Model(); if (f(m, p => p.Bids, p => p.Items, p => p.Count, p => p > 0)) { Debug.WriteLine("f"); } if (tc(() => m.Bids.Items.Count > 0)) { Debug.WriteLine("tc "); } if (m.Bids != null && m.Bids.Items != null && m.Bids.Items.Count > 0) { Debug.WriteLine("plain"); } 
+4
source share

All Articles