Reputation: 1165
Lets say I have an class with two properties of type string
And there are the following restrictions
What is the best way to define the properties whose value is dependent on one another and also changes made in one property should trigger setter property of the other?
Upvotes: 3
Views: 3025
Reputation: 726489
You have lots of choices here:
using
statement.Upvotes: 3
Reputation: 60498
You could implement this logic in the setters for each property, but I would question the wisdom of that.
It would probably be better to either have a Validate
method on the object that would check the state of those properties or have another object responsible for performing the validation and either returning errors or making changes to the object as appropriate.
Upvotes: 0
Reputation: 30698
You need to add validation in the property setter.
string prop1;
string prop2;
string Prop1
{
get { return prop1;}
set
{
if (!( Prop2 == "Test2" && value == "Test1"))
{
Prop1 = value;
}
... Add other condition here
}
}
string Prop2
{
get { return prop1;}
set
{
// set Prop2 based on Prop1
}
}
Upvotes: 5
Reputation: 26727
you are in charge of coding the "logic" you need perhaps in the property setter (kind of validation)
I would use the specification patter to extract the validation logic and make it testable as well
http://devlicio.us/blogs/jeff_perrin/archive/2006/12/13/the-specification-pattern.aspx
Upvotes: 0