The sample class in the C # Class Description Guide (page 137) does not invoke the class validation method for a specific field from within only the class constructor. Thus, basically the class of samples allows you to create an object with bad data and gives only an error for this data when you call a field property, which then performs a check. So, now you have a bad object, and he does not know about it until this moment.
I never understood why they do not just call a property from the constructor, thereby throwing an error right away if bad data is detected during initialization? I emailed them to no avail ...
I usually use the following format, invoking my properties from my constructors - does this proper structure validate initialization data? tee
class Foo
{
private string _emailAddress;
public Foo(string emailAddress)
{
EmailAddress = emailAddress;
}
public string EmailAddress
{
get { return _emailAddress; }
set
{
if (!ValidEmail(value))
throw new ArgumentException
(string.Format
("Email address {0} is in wrong format",
value));
_emailAddress = value;
}
}
private static bool ValidEmail(string emailAddress)
{
return Regex.IsMatch
(emailAddress, @"\b[A-Z0-9._%+-]+" +
@"@[A-Z0-9.-]+\.[A-Z]{2,4}\b",
RegexOptions.IgnoreCase);
}
}
source
share