How can I put validation in the getter and setter methods in C#?

Yes, you will have to create a backing field:

string _phoneNumber;

public string PhoneNumber
{
    get
    {
        return _phoneNumber;
    }
    set
    {
        if (value.Length <= 30)
        {
            _phoneNumber = value;
        }
        else 
        {
            _phoneNumber = "EXCEEDS LENGTH";
        }
    }
}

Keep in mind that this implementation is no different from an automatically implemented property. When you use an automatically implemented property you are simply allowing the compiler to create the backing field for you. If you want to add any custom logic to the get or set you have to create the field yourself as I have shown above.


You do not necessarily need a local variable. Theoretically, you could implement whatever functionality you want within a get/set property. But, in your example, you have a recursive access of your get/set property what makes no sense in the way it is implemented. So, in your concrete case, you will need a local variable, that's right.


I would do something like this as to avoid a NullReferenceException as well as shorten the overall code.

public string PhoneNumber
{
    get { return _phoneNumber; }
    set 
    {
        var v = value ?? string.Empty; 
        _phoneNumber = v.Length <= 30 ? v : "EXCEEDS LENGTH"; 
    }
}
private string _phoneNumber;