Auto-implemented getters and setters vs. public fields

tclem picture tclem · Sep 21, 2008 · Viewed 34.2k times · Source

I see a lot of example code for C# classes that does this:

public class Point {
    public int x { get; set; }
    public int y { get; set; }
}

Or, in older code, the same with an explicit private backing value and without the new auto-implemented properties:

public class Point {
    private int _x;
    private int _y;

    public int x {
        get { return _x; }
        set { _x = value; }
    }

    public int y {
        get { return _y; }
        set { _y = value; }
    }
}

My question is why. Is there any functional difference between doing the above and just making these members public fields, like below?

public class Point {
    public int x;
    public int y;
}

To be clear, I understand the value of getters and setters when you need to do some translation of the underlying data. But in cases where you're just passing the values through, it seems needlessly verbose.

Answer

Dexter picture Dexter · Sep 21, 2008

I tend to agree (that it seems needlessly verbose), although this has been an issue our team hasn't yet resolved and so our coding standards still insist on verbose properties for all classes.

Jeff Atwood dealt with this a few years ago. The most important point he retrospectively noted is that changing from a field to a property is a breaking change in your code; anything that consumes it must be recompiled to work with the new class interface, so if anything outside of your control is consuming your class you might have problems.