It’s visual sugar, but I like it better than:
if (foo != null) { foo.bar(); }
Here’s the extension methods:
public class Foo { public void Print() { Console.WriteLine("Hello World!"); } } public static class LambdaIfThenElse { public static bool IsNull(this T obj) { return obj == null; } public static bool IsNull(this T obj, Action action) { bool ret = obj == null; if (ret) action(); return ret; } public static bool IsNotNull(this T obj) { return obj != null; } public static bool IfNotNull(this T obj, Action action) { bool ret = obj != null; if (ret) action(obj); return ret; } public static bool Then(this bool b, Action f) { if (b) { f(); } return b; } public static bool Else(this bool b, Action f) { if (!b) { f(); } return !b; } public static bool And(this bool b, Action f) { if (b) { f(); } return b; } }
Here’s a usage example:
class Program { static void Main(string[] args) { (1 == 1).Then(() => Console.WriteLine("True")).Else(() => Console.WriteLine("False")); (1 == 1).Then(() => Console.Write("True")) .And(() => Console.WriteLine(" and also")) .Else(() => Console.Write("False")) .And(() => Console.WriteLine(" and more so")); (1 == 2).Then(() => Console.Write("True")) .And(() => Console.WriteLine(" and also")) .Else(() => Console.Write("False")) .And(() => Console.WriteLine(" and more so")); Foo foo = new Foo(); foo.IfNotNull(f => f.Print()).Else(() => Console.WriteLine("Goodbye World!")); Foo foo2 = null; foo2.IfNotNull(f => f.Print()).Else(() => Console.WriteLine("Goodbye World!")); } }
And here’s the output:
True True and also False and more so Hello World! Goodbye World!
Note how the And extension method can be used by both “then” (true) and “else” (false) sides of the conditional because the Else extension method returns !b.
Enjoy!