Frage

When We should use :

public string User { get; set; }

And When :

private string _user;
public string User
{
     get { return _user; }
     set { _user = value; }
}

And When:

public string User;

For example I have Class that containts user property. How should I decide that which one of the choices that I wrote I should use ?

War es hilfreich?

Lösung

As a general rule of thumb, you should only really use a property with a backing field when you need to do something else in the getter or the setter - validating some input, changing additional state, or raising a property changed notification, for example:

private string _user;
public string User
{
    get { return _user; }
    set
    {
        _user = value;
        this.RaisePropertyChanged(x => x.User);
    }
}

Otherwise, you can just use an auto-property:

public string User { get; set; }

You don't need a backing _user field for this.

Personally, I would avoid having public variables on classes.

Andere Tipps

There isn't a general rule, if you're in a team, it might depend on your team's agreed conventions. As a rule of thumb, using setters and getters allows you to have more control over what you can do with a property, like validating the input, formatting the output, raising an event, deciding that a property can be set / read only privately, etc.

1st (autoproperty) is basically the short form of doing the 2nd. As for the usage it is helpful in validating input, raising events, etc, eg

private string _user;
public string User
{
    get { return _user; }
    set
    { 
        if(!(value == ""))
            _user = value; 
    }
}

In any case it is advisable to use getters and setters.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top