I'm newish to C#, being mainly Java oriented. I have a field _config
which needs to be a value from 1 to 8, and I have this code which checks to make sure I can only set _config
to 1-8. If the value given for set is "invalid", _config
becomes -1.
public int Config {
get
{
return _config;
}
set
{
if (value > 8 || value < 1)
{
_config = -1;
}
else
{
_config = value;
}
}
}
private int _config; // the actual field that the property 'Config' refers to.
This feels really weird to me, but it does what I need it to do. I'm also thinking about having the setter throw an exception instead of setting _config
to -1 when given an invalid value. Am I using Properties correctly, or have I completely misunderstood the point of them?
Range[2,7]
attribute for this property. Validate an entire model at once instead of individually for each property. If an "invalid" value is allowed, make itnull
instead of-1
, which other may find confusing. \$\endgroup\$[Range]
but I still don't fully understand it. Say I set the range attribute like so:[Range(1, 8, ErrorMessage = "Helpful error message.")]
What happens when I set an invalid value? Do I get the error message to console or elsewhere? Does this stop the code from continuing to execute? Can I somehow customize this error message portion? \$\endgroup\$actionContext.ModelState.IsValid
. This is a built-in property that validates the entire model and generates a response with any/all appropriate error messages. \$\endgroup\$