Created
October 26, 2015 18:20
-
-
Save marcin-chwedczuk/c59930361d984fe1981a to your computer and use it in GitHub Desktop.
Simulating ?. operator in C# 5
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
using System; | |
public static class ObjectHelpers { | |
public static TResult WhenNotNull<T, TResult>(this T @object, Func<T,TResult> expression) | |
//where T: class | |
where TResult: class | |
{ | |
if (@object == null) | |
return null; | |
return expression(@object); | |
} | |
} | |
public static class StructHelpers { | |
public static TResult? WhenNotNull<T,TResult>(this T @object, Func<T,TResult?> expression) | |
//where T: class | |
where TResult: struct | |
{ | |
if (@object == null) | |
return null; | |
return expression(@object); | |
} | |
} | |
public class ClassX { | |
public ClassX Data { get; set; } | |
public override string ToString() { | |
return "ok"; | |
} | |
} | |
public class Program | |
{ | |
public static void Main() | |
{ | |
Console.WriteLine("START"); | |
var data = new ClassX { | |
Data = new ClassX { | |
Data = null | |
} | |
}; | |
var foo = data | |
.WhenNotNull(x => x.Data) | |
//.WhenNotNull(x => x.Data) | |
.WhenNotNull(x => x.ToString()) | |
.WhenNotNull(x => (int?)x.Length); | |
Console.WriteLine(foo); | |
Console.WriteLine("STOP"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment