Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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