A sample class in "C# Class Desing Handbook" (pg 137) does not call the classes validation method for a specific field from inside the classes only constructor. So basically the sample class allows you to create an object with bad data and only throws an error for that data when you call the field's property which does validation on it then. So you now have a bad object and don't it know until after the fact.
I never understood why they don't just call the property from the constructor thus throwing an error immediately if bad data is found during initialization? I've emailed them to no avail...
I tend to use the following format by calling my properties from my constructors - is this proper structure to validate initialization data? ty
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);
}
}