Create a get/set for the Cpf string, which verifies that it has 11 digits, being numbers?

Asked

Viewed 251 times

0

    private static string cpf;

    public bool CPF = cpf.Length == 11 && cpf.All(char.IsDigit);

    public string Cpf
    {
        get 
        { 
            return cpf;  
        }

        set 
        {
            if(CPF)
                cpf = value;
        }
    }

When I try to create property with operators { get; set; } this way occurs this error:

"An unhandled Exception of type 'System.Nullreferenceexception' occurred in Estacionamento.exe Additional information: Object Reference not set to an instance of an Object."

1 answer

2

I think the best option for you is to use a regular expression because you can have a better control than you are validating.

And the mistake you’re making is because you’re validating outside of Setter.

Regex regex = Regex("[0-9]{3}\.?[0-9]{3}\.?[0-9]{3}\-?[0-9]{2}");

private static string cpf;

public string Cpf
{
    get { return cpf;  }
    set {
        if(regex.IsMatch(value))
        {
            cpf = value;
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.