# Need help working out set RSS

## 5 replies

Last post Aug 24, 2017 07:46 AM by Velen

• EnenDaveyBoy

Participant

1517 Points

2226 Posts

### Need help working out set

Hi

I know what get;set; does, but i get confused when they get complicated, i  know how to use get seperatly, but i am now using fields to do some calculations and i want these to be done once, so i know i need to use set, and this bit i don't understand fully.

in a model I have a field

public decimal Price {get;set;}

public decimal Tax{get;set;}

Now i can use

public decimal Total
{
get
{
return Price + Tax;
}
}

but how do i set the Total so it only does the calculation once? and will it on re set if i change something?

• markfitzme

All-Star

25831 Points

5818 Posts

### Re: Need help working out set

With a calculated field set is useless. You will still use a get, but in a different way.

Try something like this:

```private decimal? m_Total = null;

public decimal Total
{
get
{
if(!m_Total.HasValue)
{
m_Total = Price + Tax;
}
return m_Total.Value;
}
}```

Don't forget to mark useful responses as Answer if they helped you towards a solution.
• EnenDaveyBoy

Participant

1517 Points

2226 Posts

### Re: Need help working out set

I am using this in my viewmodels mainly if i set m_Total to private i won't be able to set it in mapping.

I don't suppose you can explain the issue so i know for future reference.

• DA924

Participant

1011 Points

1104 Posts

### Re: Need help working out set

Maybe, you should be looking into Mutator.

https://www.techopedia.com/definition/27741/mutator-c-sharp

• EnenDaveyBoy

Participant

1517 Points

2226 Posts

### Re: Need help working out set

#### DA924

Maybe, you should be looking into Mutator.

https://www.techopedia.com/definition/27741/mutator-c-sharp

the issue i was refering to was how using a set would still use a get, and why setting that to private is a better way, the example is the posters not mine, i don't know if its a good one or not.....hence the question.

• Velen

Participant

1070 Points

397 Posts

### Re: Need help working out set

Hi enendaveyboy,

The set accessor can be used as following ways:

1. We want a property to be read only, so we could remove the set accessor.

2. We want to raise some events when the property is assigned a value.

3. We want to do some validation when the property is assigned a value: We could write some logic to do the validation in the set accessor method. If the value doesn't pass the validation, through an exception.

#### enendaveyboy

and why setting that to private is a better way

Whether set the accessor to private or not, it is due to your specific scenario. If you want the property can be accessed only in the current classs, you could set it to private.

If you have any other questions, please feel free to contact me any time.

Best Regards
Velen

MSDN Community Support