views:

25

answers:

3

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?

+2  A: 

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.

Reed Copsey
Ok... so maybe I should have three properties? One for the raw value and one for the calculated value maybe?
Jason
+1 for the design advice. Another option would be to make two different classes, since they have drastically different semantics.
Jeff Sternal
@Jason: Potentially - though I agree with Jeff in that 2 classes may make more sense. If you want a single class, I'd use a method, not a property setter, to set the percentage. It's doing a calculation, which suggests "method" to me, not prop setter..
Reed Copsey
this is a good answer, but my problem was solved just by modifying the value in the `get`. I know it's not necessarily good design, but it's working! Thank you for your help
Jason
A: 

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

Nate Bross
+1  A: 

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.

Vivek
thanks. this solved my problem!
Jason