Should classes internally assign to fields or properties

JasinCole

Well-known member
Joined
Feb 16, 2023
Messages
66
Programming Experience
1-3
I got another dumb question, but my google searches are coming up empty.

I get the reason for properties, when one wants to expose an internal field as an API to consumers.
I also assume that public fields and private properties don't make a whole lot of sense and are rare to see.

is there any criteria where one should prefer properties with private sets instead of fields? I guess what I am asking for is some rational on how others approach this when writing code? What's your goto and when do you decide to changes things?
 
"Properties with private sets" is for when you want an external read only access to values your class decides internally. The odometer in your car, for example.
 
Private properties may make sense if you have logic that should always execute as part of a set or get. Perhaps your property is backed by a dictionary, for example, or it does something code-wise to retrieve a dynamic element, like the current row of a bindingsource (casting it back to the object it truly is)
 
Then I guess a good design practice is to always use fields unless there is a need for external access or possibly a need to do some work prior to accessing a variable?

I guess what I was originally thinking was when using MVVM toolkit my classes have private fields and whether i should be assigning them directly inside of class methods or using the property accessors. But now that I think about it, the former would not notify the property change and would leave my UI in a state that isn't current with the state of the object.
 

Latest posts

Back
Top Bottom