Running readonly properties

So basically I came across some readonly properties on this one class, which the class author told me that I can make certain tasks possible. The problem is that most of the time they get their value through manipulation, and not directly from the private variable in the class.

Example:

 public decimal? AccruedInterest { get { if (this.Result != null) { return this.GetExchangedCurrencyValue(this.Result.AccruedInterest.GetValueOrDefault(decimal.Zero)); } return null; } } 

So, if I want to add a setter, I donโ€™t want to worry about setting this Result object, because I'm not sure that if it returns, it will be drawn correctly.

Can I do something like this?

 private decimal? _AccruedInterest; public decimal? AccruedInterest { get { if (this._AccruedInterest.HasValue) { return this._AccruedInterest.Value; } if (this.Result != null) { return this.GetExchangedCurrencyValue(this.Result.AccruedInterest.GetValueOrDefault(decimal.Zero)); } return null; } set { this._AccruedInterest = value; } } 

Or do any of you see problems that may arise due to this (in addition to being changed now)?

+4
source share
2 answers

Well, your only problem with this is to set the value to null, and you want your property to return null, and not evaluate the if statement.

But you cannot let them set to null, in which case you must add validation to the installer.

 set { if (value == null) throw new NullArgumentException("AccruedInterest"); this._AccruedInterest = value; } 

If they are set to null, you will probably need another boolean flag to see if the value is set.

 private bool _accruedInterestSet; private decimal? _accruedInterest; public decimal? AccruedInterest { get { if (this._accruedInterestSet) { return this._accruedInterest; //don't return .Value in case they set null } if (this.Result != null) { return this.GetExchangedCurrencyValue(this.Result.AccruedInterest.GetValueOrDefault(decimal.Zero)) ; } return null; } set { this._accruedInterestSet = true; this._AccruedInterest = value; } } 
+3
source

I donโ€™t know how this should work, but syntactically I donโ€™t see anything bad in your code.

0
source

Source: https://habr.com/ru/post/1381503/


All Articles