Validating properties in c#

lexeme picture lexeme · Feb 9, 2011 · Viewed 31.7k times · Source

let's suggest I got an interface and inherit class from it,

internal interface IPersonInfo
{
    String FirstName { get; set; }
    String LastName { get; set; }
}
internal interface IRecruitmentInfo
{
    DateTime RecruitmentDate { get; set; }
}

public abstract class Collaborator : IPersonInfo, IRecruitmentInfo
{
    public DateTime RecruitmentDate
    {
        get;
        set;
    }
    public String FirstName
    {
        get;
        set;
    }
    public String LastName
    {
        get;
        set;
    }
    public abstract Decimal Salary
    {
        get;
    }
}

then how do I validate strings in collaborator class? Is it possible to implement inside properties?

Answer

Fredrik Mörk picture Fredrik Mörk · Feb 9, 2011

Yes, but not using auto-properties. You will need to manually implement the properties with a backing field:

private string firstName;

public String FirstName
{
    get
    {
        return firstName;
    }
    set
    {
        // validate the input
        if (string.IsNullOrEmpty(value))
        {
            // throw exception, or do whatever
        }
        firstName = value;
    }
}