Conditional Property?  
Author Message
uncle hammy





PostPosted: Visual C# Language, Conditional Property? Top

How can I make a class property available only if the class state meets certain criteria.

For example, if I have a class "Dog" with properties "CroppedTail" and "TailLength".  I only want "TailLength" property to be visible to the user if "CroppedTail" is false.

Thanks,

Hammy



Visual C#12  
 
 
Oligarchy





PostPosted: Visual C# Language, Conditional Property? Top

I guess the question is why   set taillength to 0 if it is cropped and then check if that value is zero to tell it is cropped or not.. 

 


 
 
timvw





PostPosted: Visual C# Language, Conditional Property? Top

To me it seems that you want subclasses... (One for croppedtails... and one for nocroppedtails (and a taillength property)).


 
 
Matthew Watson





PostPosted: Visual C# Language, Conditional Property? Top

Or just throw an exception in the TailLength property if CroppedTail is false.

I really wouldn't go down the route of having a base Dog class and a subclass for dogs with tails...

 
 
Mads Torgersen - MSFT





PostPosted: Visual C# Language, Conditional Property? Top

The all-out solution would be to have a Tail class with subclasses CroppedTail and UncroppedTail, then have a Tail property on the dog. Much better than subclassing the whole dog, and allows you to optionally crop the tail of a dog dynamically (if the Tail property is settable).

Of course this is a silly example, but in the kind of realistic cases that probably underlie your question, I find that there is often an aspect that is natural to factor out in a separate class.



 
 
uncle hammy





PostPosted: Visual C# Language, Conditional Property? Top

Took me a while to get back to this thread.

Thanks for the replies, I will probably go with the sub class.