One of the important parts of object-oriented programming is encapsulation, but public properties / fields tend to break this encapsulation. Under what circumstances does a public property or field actually make sense?
Note: I only use the term 'property' or 'field' because terminology varies between languages. In general, I mean a variable that belongs to an object that can be accessed and set from outside the object.
Use of properties makes your code more object oriented. By making member variables public, you are exposing your implementation. Save this answer.
Consider using a property if the member represents a logical attribute of the type. Do use a property, rather than a method, if the value of the property is stored in the process memory and the property would just provide access to the value.
Fields can be marked as public, private, protected, internal, protected internal, or private protected. These access modifiers define how users of the type can access the fields. For more information, see Access Modifiers. A field can optionally be declared static.
Conclusion. In almost all cases, fields should be private. Not just non-public, but private. With automatic properties in C# 3, there's basically no cost in readability or the amount of code involved to use a property instead of a field.
Yes, there are sometimes good reasons. Information hiding is usually desirable. But there are some occasional exceptions.
For example, public fields are reasonable and useful for:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With