Search code examples
c#-3.0automatic-properties

Automatic Properties Problem


At the moment i'm useing .Net 3.0 but I don't get it how to use Automatic Properties .

For example if i want write this sample code via Authomatic Properties , What should i do ?

private string _name = string.Empty;
private string _family = string.Empty;
//A field with default value
private DateTime _releaseDate = System.DateTime.Now;


//ReadOnly Property
public string Name
{
    get {return _name; }
}

//enforce validation rules on setting 
public string Family
{
    get { _family; }
    set
    {
        if (value.Length < 3)
            return new Exception("Family need at least 3 character long");
        else
            _family = value;
    }
}

// A property from two other fields
public string FullName
{
    get { return _name + " " + _family; }
}

Thank you All for your responding , I got my answer


Solution

  • You can't.

    An Automatic Property simply creates a private backing field for you, and hides that from you. If you need to have logic in your property, you should implement it yourself.

    With Automatic Properties you must have both a getter and a setter, but you can make the setter private eg:

    public string Foo { get; private set; }
    

    By the way, you can't return an exception from a string property. Exceptions should be thrown, not returned.

    public string Family
    {
        get { _family; }
        set
        {
            if (value.Length < 3)
                return new Exception("Family need at least 3 character long");
            else
                _family = value;
        }
    }
    

    This should probably read:

    public string Family
    {
        get { _family; }
        set
        {
            if (value.Length < 3)
                throw new Exception("Family need at least 3 character long");
            else
                _family = value;
        }
    }