Search code examples
oopencapsulationpublic-fields

In what cases should public fields be used instead of properties?


Possible Duplicate:
Public Data members vs Getters, Setters

In what cases should public fields be used, instead of properties or getter and setter methods (where there is no support for properties)? Where exactly is their use recommended, and why, or, if it is not, why are they still allowed as a language feature? After all, they break the Object-Oriented principle of encapsulation where getters and setters are allowed and encouraged.


Solution

  • That's hard to tell, but in my opinion public fields are only valid when using structs.

    struct Simple
    {
        public int Position;
        public bool Exists;
        public double LastValue;
    };
    

    But different people have different thoughts about:

    http://kristofverbiest.blogspot.com/2007/02/public-fields-and-properties-are-not.html

    http://blogs.msdn.com/b/ericgu/archive/2007/02/01/properties-vs-public-fields-redux.aspx

    http://www.markhneedham.com/blog/2009/02/04/c-public-fields-vs-automatic-properties/