Multiply Value in Set Backing Field in C#

1.6k Views Asked by At

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.

2

There are 2 best solutions below

2
On BEST ANSWER

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:

private decimal someDecimal;

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:

public decimal SomeDecimal
{
    get
    {
        return this.someDecimal / 100;
    }
    set
    {
        this.someDecimal = value * 100;
    }
}

Edit: Your concern about loss of accuracy from floating-point arithmetic might be inapplicable in this case. Unlike float and double, 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.

1
On

When you reference this.SomeDecimal within the getter and setter for SomeDecimal you are creating an infinite recursion.

You want to create a private field that stores the true value, then use the property to get and set it according to your scheme for multiplying/dividing it.

private decimal _someDecimal;
public decimal SomeDecimal
{
    get
    {
        return _someDecimal / 100;
    }
    set
    {
        _someDecimal = value * 100;
    }
}