Skip to content

Instantly share code, notes, and snippets.

@nimacks
Last active August 29, 2015 13:58
Show Gist options
  • Save nimacks/9943430 to your computer and use it in GitHub Desktop.
Save nimacks/9943430 to your computer and use it in GitHub Desktop.
public static class ObjectExtensions
{
/// <summary>
/// Acts as a null dereference operator
/// </summary>
/// <typeparam name=”T”> Type of Object for null check</typeparam>
/// <typeparam name=”TResult”> resulting type of the expression</typeparam>
/// <param name=”item”> Object to check for null on </param>
/// <param name=”deriver”> delegate to return result</param>
/// <returns></returns>
public static TResult NullSafe<T, TResult>( this T item, Func<T, TResult> deriver)
{
return Nullify(item, deriver, default(TResult));
}
public static TResult NullSafe<T, TResult>( this T item, Func<T, TResult> deriver, TResult defaultValue)
{
if (item == null)
return defaultValue;
return deriver(item);
}
}
***************************************************
Usage:
if( javascriptDeveloper.NullSafe(e=> e.Supervisor)
.NullSafe(s => s.Manager)
.NullSafe(p =>p.Boss)
.NullSafe(q => q.Name))
{
//do something with the address
Console.WriteLine(javascriptDeveloper.Supervisior.Manager.Boss.Name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment