Last active
August 29, 2015 14:04
-
-
Save omidkrad/57e386b7c3c983bbe5d1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// This is an attempt to implement the Null-propagating operator ?. as extension methods. | |
// | |
// I was not able to do it in a single method that would work with both value types and | |
// reference types as return type. Maybe there's a way to do it or use overloads? | |
public static class ExtensionMethods | |
{ | |
/// <summary> | |
/// Use this method to safely invoke properties, methods or other members of a nullable | |
/// object. It will perform a null reference check on the object and if it is not null will | |
/// invoke the specified expression. The expression has to return a reference type. | |
/// </summary> | |
/// <returns>Returns a reference type.</returns> | |
public static TResult IfNotNull<T, TResult>(this T obj, Func<T, TResult> func, Func<TResult> ifNull = null) | |
where TResult : class | |
{ | |
return (obj != null) ? func(obj) : (ifNull != null ? ifNull() : default(TResult)); | |
} | |
/// <summary> | |
/// Use this method to safely invoke properties, methods or other members of a nullable | |
/// object. It will perform a null reference check on the object and if it is not null will | |
/// invoke the specified expression. The expression has to return a value type. | |
/// </summary> | |
/// <returns>Returns a nullable value type.</returns> | |
public static TResult? IfNotNullVal<T, TResult>(this T obj, Func<T, TResult> func, Func<TResult> ifNull = null) | |
where TResult : struct | |
{ | |
return (obj != null) ? func(obj) : (ifNull != null ? ifNull() : default(TResult)); | |
} | |
public static void Dump(this object obj) { | |
Console.WriteLine(obj); | |
} | |
} | |
void Main() | |
{ | |
// methods can be chained | |
DateTime? dt = DateTime.Today; | |
dt.IfNotNull(d => d.Value.ToLongDateString()) | |
.IfNotNull(s => s.ToUpper()) | |
.IfNotNull(s => s.PadLeft(40)) | |
.Dump(); | |
// use this other method if a value type is retuned | |
"STRING".IfNotNullVal(s => s.Length) | |
.Dump(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment