Skip to content

Instantly share code, notes, and snippets.

@marcin-chwedczuk
Created October 26, 2015 18:20
Show Gist options
  • Save marcin-chwedczuk/c59930361d984fe1981a to your computer and use it in GitHub Desktop.
Save marcin-chwedczuk/c59930361d984fe1981a to your computer and use it in GitHub Desktop.
Simulating ?. operator in C# 5
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