'Can you do calculations in the get/set ? c#

Can you do a calculation in the set clause? and it then returns the total when implemented?`

    public decimal TotalCost
     { 
      set
      { this.costTotal = (decimal)prodCost + (decimal)shipping + (decimal)insurance)}
       get
      { return this.costTotal}
     }


Solution 1:[1]

Can you do a calculation in the set clause?

Absolutely. However, in your specific case, it is not clear why would you do that. The point of a setter is to allow users of a class to safely manipulate fields of its objects. This is done using the value keyword. Since you are only interested in calculating a value using existing data, there is no reason to even use a setter. it seems more suitable to do the calculation in a getter only property:

public decimal TotalCost
{ 
    get
    {
        return (decimal)prodCost + (decimal)shipping + (decimal)insurance);
    }
}

A shorter version of the above code:

public decimal TotalCost => (decimal)prodCost + (decimal)shipping + (decimal)insurance;

Solution 2:[2]

What others said, but maybe you're looking for a method:

public decimal CostTotal { get; private set; }

(...)

public void SetTotalCost(decimal prodCost, decimal shipping, decimal insurance)
{
   this.CostTotal = prodCost + shipping + insurance);
}

Solution 3:[3]

I suggest the below code for reading and writing your property.

private decimal totalCost;
public decimal TotalCost
     { 
       get { return totalCost = (decimal)prodCost + (decimal)shipping + (decimal)insurance);}
       set { totalCost = value;}
     }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 tymtam
Solution 3 Tim O.