CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Null Extension Methods - Oh My!

106 Views
Copy Code Show/Hide Line Numbers
The following extensions methods can help you in the situation below:
 
        public static TResult IfNotNull<TSource, TResult>(this TSource obj, Func<TSource, TResult> func)
        {
            return IfNotNull(obj, func, default(TResult));
        }
        public static TResult IfNotNull<TSource, TResult>(this TSource obj, Func<TSource, TResult> func, TResult defaultIfNull)
        {
            return obj == null ? defaultIfNull : func(obj);
        }
 
 
Instead of ...
 
   if (null != tree && null != tree.Headings && tree.Headings.Count > 0) { ... }
 
you can do this ...
 
   if (tree.IfNotNull(t => t.Headings).IfNotNull(headings => headings.Count) > 0) { ... }
 
 
ABPS: http://code.logos.com/blog/2008/01/nullpropagating_extension_meth.html
by Kevin
  September 02, 2010 @ 8:01am

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate