Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Abusing Extension Methods and Null Continuation

0.00/5 (No votes)
31 Dec 2019 1  
Please don't do this!

Introduction

Yet another crazy way to write if-then statements without writing if. Really, don't do this, it's just an experiment in what's possible. The main reason not to do this is that extension methods and the ?. null continuation operator were not intended for this purpose, and you'll confuse the heck out of other programmers when they encounter this crazy code.

The Basic If

The if statement is one of the cornerstones of a program, slightly more readable than its assembly language counterparts "branch if equal", "branch if not equal", "branch if greater", and so forth. In almost every language, you write the following, which tests the truth of the condition:

if (somethingIsTrue)
{
  doSomethingWhenTrue();
}

For our little demonstration, we'll use this code:

public void Test()
{
  if (true)
  {
    Write("The usual way");
  }
}

public void Write(string msg)
{
  Console.WriteLine(msg);
}

So far so good. Everyone can read that, even those without any programming experience!

WhenTrue

Now let's introduce an extension method:

public static void WhenTrue(this bool condition, Action action)
{
  if (condition)
  {
    action();
  }
}

And now, using extension and anonymous methods, we can write:

true.WhenTrue(() => Write("Using an extension method"));

Now we have something less readable unless you're familiar with anonymous methods (aka "fat arrow" methods) but you still get the basic idea -- The anonymous method, as an Action, is executed when the condition on the left is true, and:

false.WhenTrue(() => Write("Should be false!!!"));

When not true, it doesn't. This works of course:

int a = 1;
int b = 1;
(a == b).WhenTrue(() => Write("A equals B"));

But the () => syntax is a lot of arcane symbol incantation and what is occult in the anonymous method is that there is a hidden closure on this, such that the Write method is found in the class making the call.

Continue if Not Null

If we introduce a different extension method:

public static T WhenTrue<T>(this bool condition, T me) where T : class
{
  return condition ? me : default(T);
}

lo-and-behold, we can write:

true.WhenTrue(this)?.Write("Using null continuation");
false.WhenTrue(this)?.Write("Should also be false!!!");

Oh my. Now we have entered into the land of occult initiation that the materialist developer cannot immediately understand and will (with good reason) deny even exists! Why are we passing in this? Why does the extension method return null? How is it possible to continue with a method of the class?

In the occult school of programming, the beauty of this is that this is returned by the extension method when the condition is true, and with the arcane knowledge that T is a class, default(T) always returns null!

Where Do You Want This?

The above syntax is sort of backwards, particularly since this is a parameter of WhenTrue, which makes reading the code a bit like reading Reverse Polish Notation. Let's try this instead:

public static T WhenTrue<T>(this T me, bool condition) where T : class
{
  return condition ? me : default(T);
}

Funny how the implementation of the extension method is exactly the same, all we've done is swapped the parameters such that instead of the extension method being available to a bool type, it's available to any class type. So now we can write something a wee bit more left-to-right:

this.WhenTrue(true)?.Write("Another truth");
this.WhenTrue(false)?.Write("Another falsehood");

Coalesce Your Ascension or Else!

So what about the else, a necessary kindred spirit of if? Well, try this, using the null coalescence operator:

var _ = this.WhenTrue(true)?.Write("Another truth") ?? Write("Not truth");
var __ = this.WhenTrue(false)?.Write("Another falsehood") ?? Write("False!");

This bit of magic requires that Write returns a value and that we assign that value to something we probably don't care about, so Write now looks like this:

public int Write(string msg)
{
  Console.WriteLine(msg);
  return 0;
}

Truly, we have entered into the realm of the esoteric!

And Thus...

We conclude the year 2019 with how extension methods and null continuation operators can ascend to do something the designers probably never intended.

The grand master of coding will also note that statements like:

this.WhenTrue(true)?.Console.WriteLine("Go to h***");

are not possible because, of course, Console is not a member of this unless you write a static member of this called Console that wraps the functionality of System.Console...run away!

History

  • 31st December, 2019: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here