3

I have been programming classes recently and using private fields and get/set methods to access these private fields, A friend suggested to me that I use Auto Implemented properties as It would save me time programming. I was wondering what the primary differences between these two methods were and whether Auto Implemented properties keep the value of a "field" private at run-time.

For example my friend said I should use this:

public int MyProperty { get; set; }

Previously I was using something similar to this:

private int field;

public void setField(int i)
{
    field = i;
}
public int getField()
{
    return field;
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
gcharnley
  • 39
  • 1
  • (1) less code (2) let the outer world understand it clearly that, you are basically having a data member in your class and letting the outer world access it, rather than having two separate methods which may or may not be related. – Arghya C Nov 23 '15 at 10:14
  • 1
    And yes, auto-properties use a (private) field, but it is generated by the compiler. With reflection you can find out its name is `k__BackingField` – Dennis_E Nov 23 '15 at 10:16
  • 3
    I disagree the question is duplicate. The question is not what the difference is, but that the advantage of one over the other is. – Patrick Hofman Nov 23 '15 at 10:17
  • @PatrickHofman The linked question does have answers that give the benefits though, so ultimately it is a duplicate. – DavidG Nov 23 '15 at 10:20
  • Meh, sort of indeed. Not sure if I really see that as a duplicate @DavidG – Patrick Hofman Nov 23 '15 at 10:21
  • @PatrickHofman Possibly, I'm happy to dupe it though, there's a lot of good info in there and some great answers. – DavidG Nov 23 '15 at 10:22
  • @DavidG see the question is over get-set methods? Not fields... – Patrick Hofman Nov 23 '15 at 11:27
  • Useful reading material on [fields vs. properties](http://stackoverflow.com/q/295104/993547). – Patrick Hofman Nov 23 '15 at 11:29

1 Answers1

1

Not only is it a better design to prevent direct access to fields, which is arguable, also the framework prefers properties over fields (and methods in some situations) for a number a things.

One of them is data binding. You can't data bind to a field, only to a property. Also, it allows you to set access modifiers to allow reading, but not writing a property for example.

Properties are also easier to write than your Java style properties. In the end the code is the same (since properties become methods eventually), but for you as a coder, it is much easier.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325