I'm trying to write an "onchange" event for a C# class that I have. The idea would be to capture anytime the class was instantiated or a property was changed and fire off some code to evaluate the "health" of the object, then set a property of the class to true or false based off of the method being invoked. My initial attempts were to simply call a private method in the setter of each property as such:
string _source = null;
public string Source
{
set
{
this._source = value;
OnClassChange();
}
get { return this._source; }
}
string _dest = null;
public string Dest
{
set
{
this._dest = value;
OnClassChange();
}
get { return this._dest; }
}
bool _isValid;
public bool IsValid
{
get { return _isValid; }
}
void OnClassChange()
{
_isValid = (_source == null) ? false : true ;
_isValid = (_dest == null) ? false : true;
}
but this seems sort of clunky and not elegant... I'd like to use some sort of listener, then in my OnClassChange() block simply loop through all the private properties of the class, determine the type of property and invoke some logic to determine if the values of the property is valid or not in a loop.
You don't really need a field for this at all - unless the validation is costly (so you want to avoid recomputing it each time it's requested) you can just have:
public string Source { get; set; }
public string Destination { get; set; }
public bool IsValid { get { return Source != null && Destination != null; } }
In C# 6 the IsValid
code would be be even simpler:
public bool IsValid => Source != null && Destination != null;
See more on this question at Stackoverflow