Last active
August 29, 2015 13:58
-
-
Save nimacks/9943430 to your computer and use it in GitHub Desktop.
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
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