If-then-else as lambda expressions

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!

Advertisements

One thought on “If-then-else as lambda expressions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s