3
votes

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;
}
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
And yes, auto-properties use a (private) field, but it is generated by the compiler. With reflection you can find out its name is <MyProperty>k__BackingFieldDennis_E
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
@PatrickHofman The linked question does have answers that give the benefits though, so ultimately it is a duplicate.DavidG
Meh, sort of indeed. Not sure if I really see that as a duplicate @DavidGPatrick Hofman

1 Answers

1
votes

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.