3

Whats the difference now between doing this:

public string Title { get; set; }

and this:

public string Title;

Back in the day people always said use accessor methods with private variables called by the public accessor, now that .net has made get; set; statements so simplified that they look almost the same without the private variable as just using a public only variable, so whats the point and difference?

David
  • 113
  • 1
  • 3
  • http://stackoverflow.com/questions/3195075/clean-code-should-objects-have-public-properties – onof Jul 14 '10 at 11:07
  • possible duplicate of [Properties vs. Fields: Need help grasping the uses of Properties over Fields.](http://stackoverflow.com/questions/3069901/properties-vs-fields-need-help-grasping-the-uses-of-properties-over-fields) – Igor Zevaka Jul 14 '10 at 11:08
  • I understand the need for properties over fields, but in that syntax, there is no difference now? – David Jul 14 '10 at 11:09
  • 1
    The differences are still the same. What's happened is that property syntax has started to look more like field syntax. But it's just syntax: they're completely different underneath. – Tim Robinson Jul 14 '10 at 11:10
  • Properties should start with capital letter (since they are public) and fields (which should always be private) should not. Properties have {} in signature and fields do not. – Cloudanger Jul 14 '10 at 11:59
  • possible duplicate of [Auto-implemented getters and setters vs. public fields](http://stackoverflow.com/questions/111461/auto-implemented-getters-and-setters-vs-public-fields) – nawfal Jun 03 '13 at 18:42

3 Answers3

8

I have an article on this: Why properties matter.

In short: properties are part of an API. Fields are part of an implementation. Don't expose your implementation to the world. You can change an automatically implemented property to have more behaviour (maybe logging, for example) in a source and binary compatible way. You can't do that with a field.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

The first one

public string Title { get; set; }

is a property (Which is in fact a function).

The second one

public string Title;

Is a field.

It is good to use properties to hide the implementation (Encapsulation).

Itay Karo
  • 17,924
  • 4
  • 40
  • 58
  • BUt there is not implmentation being hidden here? – David Jul 14 '10 at 11:11
  • Indeed there is not. But you might add one someday or will arise the need to change the internal implementation so you will be able to do it without changing the interface. – Itay Karo Jul 14 '10 at 11:24
0

In the second case, you can't modify the implementation of the accessor (because is not an accessor) without recompiling the dependent assemblies.

onof
  • 17,167
  • 7
  • 49
  • 85