Whats the best way to keep a number equal or greater than zero

269 Views Asked by At

What I want to achieve is to make sure that my property is always 0 or greater. The type doesn't matter.

Lets say:

var x = 3;
var y = 5;

And after x -= y x is supposed to be 0.

Currently using this way and was wondering of there is a way without member variables:

public int Coins
{
  get { return Math.Max(0, _coins); }
  set { _coins = value; }
}

Couldn't either figure out a way with uint.

All suggestions appreciated.

uint x = 3;
uint y = 5;

Expected x beeing 0 after x -= y but received unit max.

1

There are 1 best solutions below

1
Hunter Tran On

If you implement the get and set differ from the automatic properties, then you always need to declare a private member to store the value. This is by design.

Even if you use the automatic properties and don't declare the private member, the compiler will do it anyway. You just see less code, but the computer sees no differences.

Source: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties

Anyway, I would suggest 1 small change:

public int Coins
{
  get { return _coins; }
  set { _coins = Math.Max(0, value); }
}

This way, the "wrong" _coins value don't get stored. But of course, it based on your bussiness logic, so the suggested code might not the right one for you