Created
June 14, 2013 14:08
-
-
Save hoangtranwork/5782070 to your computer and use it in GitHub Desktop.
Helper extension method to help try get a non-null instance
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 Extensions | |
{ | |
/// <summary> | |
/// Try to get a non null instance of TOutput from TInput via a outputCreator func | |
/// </summary> | |
/// <typeparam name="TInput"></typeparam> | |
/// <typeparam name="TOutput">Type of the output param, need to have a default non-param constructor</typeparam> | |
/// <param name="input"></param> | |
/// <param name="outputCreator"></param> | |
/// <returns></returns> | |
public static TOutput TryGetNonNull<TInput, TOutput>(this TInput input, Func<TInput, TOutput> outputCreator) where TOutput : new() | |
{ | |
try | |
{ | |
if (Equals(input, default(TInput))) | |
{ | |
// input is null, return default output (must have default constructor) | |
return new TOutput(); | |
} | |
TOutput nonNullOutput = outputCreator(input); | |
if (Equals(nonNullOutput, default(TOutput))) | |
{ | |
// result of outputCreator function is also null, return default output | |
return new TOutput(); | |
} | |
// return the valid non-null output | |
return nonNullOutput; | |
} | |
catch (Exception) | |
{ | |
// any other case, return default output | |
return new TOutput(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment