Month: May 2015

In-line conditional and assignment operator


We have operators like +=, *= for addition & assignment, subtraction & assignment respectively. and I’m wondering why we don’t have similar operator for in-line conditional & assignment. Consider two simple operations.

a = b + a;
a = a == 0 ? b : a;

We can reduce the first statement as:

a += b;

As the ternary operator always must return a value, Should I not be able to do the following?

a =? a != 0 : b;
a =?!= 0 : b; // Now, this is kick-ass!
a =:== 0 ? b; // And this is insane.

Noticed the operator =?!= in the second item? This doesn’t exist in C or any other sane programming language, but lets play the game Mr Holmes!
Here a is the isTrue expression as well as the operand. isFalse expression is b. So, the operator implies, assign to the operand the isTrue expression(which is the operand itself as implied by ‘=?’) if the operand is not equal to 0 and otherwise, assign the isFalse expression b. You can infer the third statement the same way.

I’m aware of ?? null coalescing operator which comes close but I’m afraid I can’t check anything other than null.

C#’s extension method may look like an idea but isn’t. I tried to write something like:

/* This code doesn't work */
public static void OnFalse(this ref T item, bool condition, T onFalse)
{
    if (!condition)
    {
        item = onFalse;
    }
}

And to call it like:

a.OnFalse(a == 0, b);

The keyword ref is not supported in extension methods. The idea of returning the value is not productive as it requires you to repeat ‘a’.

There is also a specific solution for the == operator and int type.

public static int SetOnEquals(this int item, int value, int onFalse)
{
    return item == value ? onFalse : item;
}

And call like:

a = a.SetOnEquals(0, b);

This will work, but we did repeat ‘a’ there and our extension method is no longer generic.

Making it a static function,

public static void OnFalse( ref T item, bool condition, T onFalse)
{
    if (!condition)
    {
        item = onFalse;
    }
}

You can call it like:

OnFalse(ref a, a==0, b);

Let’s drop the templates again.

public static void OnEqual( ref int item, int value, int onFalse)
{
    if (item == value)
    {
        item = onFalse;
    }
}

Now the call becomes:

OnEqual(ref a, 0, b);

This is no solution. If you are crazy enough, you can chip in some thoughts!