Photo by Nathalia Segato on Unsplash

A Small C# Puzzle

Michael Moreno

--

Hey all, I know I’ve been away awhile. I have some ideas for articles churning around but I’m not yet ready to put them to the page just yet. In the meantime I thought sharing a small C# puzzle would be a nice low-effort post.

Here it is:

// Puzzle: Counting the count

void Main()
{
var counter = new Counter();

Count(
counter.Count,
counter.Count,
counter.Count > 2 ? counter.Count-- : counter.Count++
);

Console.WriteLine($"d: {counter.count}");
}

void Count(int a, int b, int c)
{
Console.WriteLine($"a: {a}");
Console.WriteLine($"b: {b}");
Console.WriteLine($"c: {c}");
}

class Counter
{
public int count;

public Counter()
{
count = 0;
}

public int Count
{
get
{
count++;

return count;
}

set
{
count = value;
}
}
}

The question is simply: what will the above code print?

It’s straightforward, but at the same time, it’s not. Try to guess what the code will print and then when you’re ready to check your answer, go ahead and execute the code.

Did you guess correctly? I guarantee at least some of you will have gotten it wrong.

Whether or not you figured out the correct answer, the takeaway here is that you should never write code like this, and you should never let your coworkers write code like this. Anyone reasonably competent in the language should be able to look at the code and know exactly what it’s doing without having to second guess themselves.

If you find yourself writing code with side effects, seemingly ambiguous execution order, or with multiple actions happening on one line, stop yourself — and rethink your approach. Maybe you’ve heard the cliche “code is read more often than it’s written”. I don’t know who first said it, but I can tell you it’s absolutely true. You should strive to make your code readable first and foremost. And this doesn’t mean peppering it with comments — that’s a rookie mistake. Instead, the code should be self-explanatory. Your code shouldn’t look like a puzzle.

Thank you for reading!

--

--

No responses yet