Checking Designer Data

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);
    }
}
+3
source share
5 answers

, , , , NullReferenceException, , emailAddress . , emailAddress IS null, ArgumentNullException. , , . , , . , , .

+2

, :

, valid

.

, , "" , .

+2

. , . , , .

- , " ", . BrokenRules, , , . , , List "" . ( ) IsValid , - .

, . (.. ), , , , , . . Etc.

+2

. , / - .

0

authentication occurs when an email address is specified. Here you want, because the email address could potentially be set later.

If you also called validation in the constructor, you must make an additional redundant validation call (one time when it is created, the other when the email address is specified in the constructor).

0
source

Source: https://habr.com/ru/post/1716158/


All Articles