Lets say you have a Class with 300 properties with no backing variables, each of those properties returns a decimal/double.
Example:
public decimal MathValue { get; set; }
Now you decided that each one of those values should be rounded.
I am looking for the simplest way to refactor this without having to rewrite all of those properties.
Something, of this equivalent that actually works :D:
public decimal MathValue { get {return Math.Round(MathValue);} set; }
No. If you need any custom logic in either getter or setter, you cannot use auto-properties.
You could create a new value type that pretends to be a decimal, but returns the rounded value. Something like this:
struct RoundedDecimal
{
public decimal Value { get; private set; }
public RoundedDecimal(decimal value) : this()
{
this.Value = value;
}
public static implicit operator decimal(RoundedDecimal d)
{
return Math.Round(d.Value);
}
}
Each property in your class should be of type RoundedDecimal
instead of decimal
.
Easiest way to refactor the code? Here's what I would do:
Now you'll need to define a set of corresponding private variables that begin with an underscore but otherwise have the same names as the properties. Start with a fresh copy of the properties from your class and perform a similar set of steps as described above.
My assumption is that each line starts with 2 tabs and there are no empty lines between properties.
Rather than having each property call Math.Round, you may want to consider defining your own utility function that they all call so that if you need to change it again, you can just change it in one place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With