How to ensure the value of property for others who depend on it?

I have a property like:

private Decimal _payout; public Decimal PayoutValue { get { return _payout; } set { _payout = value; //second part of following conditional is an enum if (Math.Abs(value) > 1 && this.PayoutType == CutType.Percent) { _payout /= 100; } } } 

As you can see, this depends on the value of PayoutType , which is simply the simplest property of enum:

 public CutType PayoutType { get; set; } 

My problem is that PayoutType doesn't seem to set before PayoutValue , so the condition below will never be true. How to force the PayoutType parameter before PayoutType is evaluated?

Thanks.

UPDATE Thank you for your answers. I probably should have mentioned that most of the time this object is connected via DataContexts or with Http.Post from my client side (MVC project), so I have no constructors. Is there any other way, or do I need to start creatively with my programming?

+4
source share
3 answers

How about this?

 get { if (Math.Abs(value) > 1 && this.PayoutType == CutType.Percent) { return _payout /100; } return _payout; } set{_payout = value;} 

So that you do not change the value that was set.

+1
source

How to force PayoutType parameter to be set before PayoutValue is calculated?

Put it in the constructor. This is the only way to enforce this rule.

Speaking of which, I would recommend against this, at least in your implementation above. Your current implementation will be very, very confusing for users. People tend to expect that setting a property and then fetching it will provide the same value.

In your case:

 decimal value = 45.3; myObject.PayoutValue = value; // Set this if (myObject.PayoutValue != value) { // This would normally be a very unexpected case! In your example, it will always be true! } 

It would be much better to potentially use two properties or a method (i.e.: SetPayoutValue(decimal value) ) to tell the user that he is not acting as a simple property.

+2
source

All necessary properties must be in the constructor of your class.

0
source

All Articles