Question

I have a property like so:

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, it is dependent upon the value of PayoutType, which is just a simple enum property:

public CutType PayoutType { get; set; }

My problem is that PayoutType doesn't seem to get set before PayoutValue is set, so the conditional below is never true. How do I force the PayoutType to be set before PayoutValue is evaluated?

Thanks.

UPDATE Thanks for your answers guys. I guess I should have mentioned that most of the time this object is bound via DataContexts or from an Http.Post from my client side (MVC project), so I don't really have any constructors. Is there any other way, or should I start getting creative with my programming?

Was it helpful?

Solution

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.

OTHER TIPS

How do I force the PayoutType to be set before PayoutValue is evaluated?

Put it in the constructor. That's the only way to enforce this rule.

That being said, I would recommend against this, at least in your implementation above. Your current property implementation will be very, very confusing to users. People tend to expect that setting a property, then immediately fetching it will provide the same value.

In your case, though:

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 (ie: SetPayoutValue(decimal value)) to clue the user into the fact that it's not acting like a simple property.

All "required" properties should be in the constructor of your class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top