C# – New automatic properties in c# 3.0, what’s the benefit?

.netc++properties

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?

Best Solution

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).