tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

True and False functions as “oneliners”

29 Jun 2020 1 mins C#

I was reading Stephen Cleary’s A New Pattern for Exception Logging blogpost and the True and False methods caught my eye and I wanted to write them as “oneliners”.

By “oneliner” I mean method that’s using expression body. If you’re looking for answer to “Why?", I don’t have it. So, let’s consider it a quick exercise in C#.

The expression body as the name implies, has to be expression and not bunch of statements in a block. I need to call an Action and return bool. Which is actually Func<bool>. Having that it’s easy to do so.

public static bool False(Action action) => new Func<bool>(() => { action(); return false; })();

You might not like the new being there, luckily casting works just fine.

public static bool False(Action action) => ((Func<bool>)(() => { action(); return false; }))();

Both versions result in same IL, so at the end of the day, it’s only about your personal preference.

And finally, as a little bit of fiddling it can be made bit more obfuscated. Or succinct?

using a = System.Action;
using b = System.Func<bool>;
class C
{
	const bool f = false;
	public static bool False(a a) => ((b)(() => { a(); return f; }))();
}

I’ll leave this exercise here, because I feel it could end up with very ugly code.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.