Reputation: 7
I got a problem with a byte property. I want the attribute to be 0 if an amount is subtracted that would set the number below 0.
My problem is that in a property I only get the value field where the calculation is already finished and the value is not negative but the amount that would have been negative subtracted from the max value of byte.
Changing the attribute type to sbyte is not option.
Is there any way to ensure that 4 minus 5 is 0 and not 255 without writing an explicit setter method and only using a getter property?
Upvotes: 0
Views: 497
Reputation: 44931
How about something like this, where the backing property is an int:
private int m_TestValue;
public byte TestValue
{
get
{
if (m_TestValue < 0)
{
return 0;
}
else
{
return (byte)m_TestValue;
}
}
set {
m_TestValue = value;
}
}
Update
Thanks to 32bitkid, I now realize the above solution will not work because any negative value will be converted to a positive value prior to reaching the setter.
The only way to solve this, other than checking the value prior to assignment, is to change the data type of the property to an int, but then provide a byte property that provides the desired functionality.
For example:
public int TestValue {get; set; }
public byte TestValueAsByte
{
get
{
if (this.TestValue < 0)
{
return 0;
}
else
{
return (byte)this.TestValue;
}
}
set
{
this.TestValue = value;
}
}
Upvotes: 1
Reputation: 113272
First, avoid byte
for general integral use. Operating on int
is faster, gives you more flexibility and byte will only save space if you pack them in, and even then the saving won't be significant until you've millions of such objects.
Now, you aren't clear where the "number that is subtracted is".
If the can't-be-negative rule is a matter of the state (rather than "it's negative really but displays as zero, and e.g. -3 plus 2 will still show zero because internally it's zero"), then enforce that rule at the point where the sutraction happens.
private void Subtract(int subtrahend)
{
value = Math.Max(value - subtrahend, 0);
}
If it should beinternally negative but display as zero then, just do that in the getter
public byte ByteForSomeReason
{
get { return Math.Max(value, 0); }
}
Or indeed, do so in a setter. What do you have against setters setting values, I would rather suspect that they'd be good at that.
Upvotes: 2