Jeyhun
Jeyhun

Reputation: 469

Declare Property in C#

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 ?

Upvotes: 1

Views: 396

Answers (3)

Octane
Octane

Reputation: 1240

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.

Upvotes: 1

Chris Mantle
Chris Mantle

Reputation: 6693

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.

Upvotes: 1

Saverio Terracciano
Saverio Terracciano

Reputation: 3915

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.

Upvotes: 1

Related Questions