1

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.

Bugrick
  • 19
  • 1

1 Answers1

6

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

Hunter Tran
  • 13,257
  • 2
  • 14
  • 23
  • For my use case it makes no difference but I actually like your change. Thanks for the explanation. – Bugrick Jan 18 '23 at 16:05