Created
April 5, 2013 15:06
-
-
Save esteewhy/5320016 to your computer and use it in GitHub Desktop.
Nifty basic things missing in .NET framework: 1. Get property without worrying about null checks: someObject.IfNotNull(o => o.Property) (Nice side-effect is that accessor code is only executed when needed. Also, it's smart enough not to return null where empty collection would fit) 2. Generate sequence out of anything, say, from a node's parents…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
namespace System.Linq | |
{ | |
public static class EnumerableExtension | |
{ | |
public static IEnumerable<T> Generate<T>(this T seed) | |
{ | |
return new T[] { seed }; | |
} | |
public static IEnumerable<T> Generate<T>(this T seed, Func<T, T> step) | |
{ | |
if (null == seed) | |
{ | |
yield break; | |
} | |
yield return seed; | |
T prev; | |
while ((null != (seed = step(prev = seed)) && !object.ReferenceEquals(prev, seed))) | |
{ | |
yield return seed; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
namespace System | |
{ | |
public static class ObjectExtension | |
{ | |
public static IEnumerable<OUTPUT> IfNotNull<INPUT, OUTPUT>(this INPUT value, Func<INPUT, IEnumerable<OUTPUT>> getResult) | |
{ | |
return null != value ? getResult(value) : Enumerable.Empty<OUTPUT>(); | |
} | |
public static OUTPUT IfNotNull<INPUT, OUTPUT>(this INPUT value, Func<INPUT, OUTPUT> getResult) | |
{ | |
return null != value ? getResult(value) : default(OUTPUT); | |
} | |
public static void IfNotNull<INPUT>(this INPUT value, Action<INPUT> action) | |
{ | |
if(null != value) | |
{ | |
action(value); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good conceptual description of the second problem in Java: http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java