views:

373

answers:

4

Hi,

Whats the benefit of:

public string User {get; set;}

over

public string User;

Since you can't access the private member in the first case, how is it any different that just making your property public?

A: 

This is a duplicated question. See here.

smink
+7  A: 

The second example is making the field public, not a property (your question). This provides a simple way of making simple properties. Properties should be your default, not public fields; the list of reasons is endless, but starts with:

  • encapsulation
  • ability to add notification
  • encapsulation
  • ability to do validation
  • encapsulation
  • data binding
  • encapsulation
  • security checking

oh - and did I mention encapsulation?

Changing from a field to a property after-the-fact is a breaking change - especially if you use a lot of "ref" code or mutable structs (yeuch).

Marc Gravell
Encapsulation is also important. I'm surprised you didn't include that in your otherwise excellent list.
Robert Rossney
oh, my bad - I'll try to remember that for next time...
Marc Gravell
+1  A: 

There can be a number of things that you must do when User value changes. Things that you don't know in advance or are not present at the time you design your classes. For example one day you realize that user value should be at least 5 characters long. If you have and property it simple to implement. If you have a public field you must change that to property and recompile all dependent code.

In essence I think it pays to explicitly separate public/API part of the our types and the private implementation details.

Did someone mentioned encapsulation ? ;)

Petar Repac