I'm looking to multiply a value in the set
backing field in C# (for an ASP.NET MVC application). I'm doing this to avoid issues with dividing floating point numbers and therefore the properties are integers that require to be multiplied and divided for the sake of appearance and then stored as decimals.
Following the answer here, I'm trying to use the backing fields to complete these operation on a property like so:
public decimal SomeDecimal
{
get
{
return this.SomeDecimal / 100;
}
set
{
this.SomeDecimal = this.SomeDecimal * 100;
}
}
I'm getting the following warning:
Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
Could anyone explain the proper way to multiply and divide the number without doing so in the view / controller.
A backing field is a separate member from your property. It's typically declared as private, of the same type as the property, and with the same name but in camelCase or with an underscore:
Then, your property is defined to read from and write to this field. In case of the setter, you use the keyword
value
to get the value that was assigned to the property:Edit: Your concern about loss of accuracy from floating-point arithmetic might be inapplicable in this case. Unlike
float
anddouble
, which are stored as base-2 representations,decimal
is stored in base 10. There should never be any loss of accuracy if you're performing simple arithmetic calculations (such as summations) on reasonable monetary values with two decimal places – the type was designed for that purpose.