Crap C# Set property

I haven’t wrote a nerdy blog with code for a while. So let’s discuss C# Properties. A basic example could look like this:

private int _amount = 0;

public int Amount
{
   get { return _amount; }
   set { _amount = value; }
}

Here we have a property called Amount and the value is a number (int = Integer). You can get the value to see what it is, and you can set a new value. You could test it out with code like this:

Amount = 50;
MessageBox.Show($"Amount: {Amount}");

We set the Amount to 50. Then display the value in a message box. So this will display “Amount: 50”.

I saw a poor implementation of this basic C# feature. When I have come across crap code, I’ve sent it to my Apprentice to see if he understands why it is bad. This one caught him out.

This example looks similar, but notice the set method. It has a hardcoded value of 0 rather than the C# keyword “value”.

private int _amount = 0;
public int Amount
{
   get { return _amount; }
   set { _amount = 0; }
}

So what happens when you do this?

Amount = 50;
MessageBox.Show($"Amount: {Amount}");

Instead of showing “Amount: 50”, it actually shows “Amount: 0“. This can easily lead to bugs, or simply confuse a developer for a few minutes. The only way the value can actually be set in that implementation is via the “backing field”, the variable called _amount. This code will show “Amount: 50”

_amount = 50;
MessageBox.Show($"Amount: {Amount}");

Bonus SQL

I saw some bad SQL which I also sent to my Apprentice. I sent him this, hoping he’d maybe test it out, or maybe read up on bit fields, but he couldn’t tell me what was wrong with it.

declare @VerificationStatus bit
set @VerificationStatus = 2

A “bit” stores a value 0 or 1. So how can it be set to 2?

When you set it to 2, it doesn’t give you an error, it just sets it to 1. Any non-zero number is set to 1. This wasn’t the intention of the developer, he should have used an int. If he had tested his code, he would have seen it insert the wrong value into the table.

Leave a comment