Last active
August 23, 2016 08:32
-
-
Save ArseniySavin/54d5d89df419642030dce432c9978487 to your computer and use it in GitHub Desktop.
Unification ternary operation
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 ConditionalExtensions | |
{ | |
/// <summary> | |
/// Unification ternary operation | |
/// </summary> | |
/// <typeparam name="T">in type</typeparam> | |
/// <typeparam name="V">out type</typeparam> | |
/// <param name="baseObject">this object</param> | |
/// <param name="exp">boolean expression</param> | |
/// <param name="firstValue">true value</param> | |
/// <param name="secondValue">alternative value</param> | |
/// <param name="defaultObject">Default value. If param baseObject and secondValue is null, this return default value</param> | |
/// <returns></returns> | |
public static dynamic Conditional<T,V>(this T baseObject, Func<T, bool> exp, dynamic firstValue, dynamic secondValue, V defaultObject) | |
{ | |
try | |
{ | |
if(baseObject != null) | |
{ | |
if(exp(baseObject).Equals(true)) | |
return firstValue; | |
else | |
return secondValue; | |
} | |
else | |
{ | |
if(secondValue != null) | |
return secondValue; | |
else | |
{ | |
if(defaultObject != null) | |
return defaultObject; | |
else | |
throw new ArgumentNullException(string.Format("Default value can not be null! Param: {0}", defaultObject.GetType().Name)); | |
} | |
} | |
} | |
catch | |
{ | |
throw; | |
} | |
} | |
/// <summary> | |
/// Unification null value | |
/// </summary> | |
/// <typeparam name="T">in type</typeparam> | |
/// <param name="baseObject">this object</param> | |
/// <param name="exp">object</param> | |
/// <param name="firstValue">true value</param> | |
/// <param name="secondValue">alternative value</param> | |
/// <returns></returns> | |
public static dynamic ConditionalNull<T>(this T baseObject, Func<T, dynamic> exp, dynamic firstValue, dynamic secondValue) | |
{ | |
if(object.ReferenceEquals(exp(baseObject), null)) | |
return firstValue; | |
else | |
return secondValue; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment