Skip to content

Instantly share code, notes, and snippets.

@esteewhy
Created April 5, 2013 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esteewhy/5320016 to your computer and use it in GitHub Desktop.
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…
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;
}
}
}
}
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);
}
}
}
}
@esteewhy
Copy link
Author

esteewhy commented Jun 7, 2013

Good conceptual description of the second problem in Java: http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment