Reputation: 24052
So basically I've come across some readonly
properties on this one class that the writer of the class told me I could make settable for a specific task. Problem is, they get their value through manipulation most of the time, not directly from a 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 that Result
object because I'm not sure if on it's way back out it's going to be drawn correctly.
Would I be able to 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 issues that could arise from this (besides the fact that it's now changeable)?
Upvotes: 4
Views: 220
Reputation: 46585
Well your only problem with this is if they set the value to be null and you want your property to return null rather than evaluate the if statement.
But you might not allow them to set null, in which case you should add a check in the setter.
set
{
if (value == null)
throw new NullArgumentException("AccruedInterest");
this._AccruedInterest = value;
}
If it is valid for them to set null, you probably need another boolean flag to tell if the value has been 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;
}
}
Upvotes: 3
Reputation: 46047
I don't know how it's supposed to work, but syntactically I don't see anything wrong with your code.
Upvotes: 0