A different way to express loop conditions in C#

dev, csharp comments edit

Today I was looking at a code sample and I noticed a rather unusual syntax in a while condition. It looked like this:

int T = Int32.Parse(Console.ReadLine());
while(T-->0)
{
    // Do stuff
}

I started looking around for –> operator assuming it’s a new addition to the language but it wasn’t listed in the C# operators list.

Playing around with this code in a sample console application I realized that it’s just a decrement operator and greater than comparison grouped together. So it’s essentially equivalent of this:

int n = 4;
while ( n-- > 1 )
{
    Console.WriteLine($"Hello World! {n}");
}

But looks better when it looks like a single operator. Same can be done with the increment and less than comparison but it a bit looks uglier:

int n = 4;
while ( n ++< 8 )
{
    Console.WriteLine($"Hello World! {n}");
}

It can also be used in a for loop:

var items = new int[] { 1, 2, 3, 4, 5 }; 
var m = 4;
for (; m --> 1 ;)
{
    Console.WriteLine($"Hello World! {m} {items[m]}");
}

which would print

Hello World! 3 4
Hello World! 2 3
Hello World! 1 2

I don’t I would use this notation in my own applications but might be helpful when reading somebody else’s code.

Resources

Comments