See other articles on the website on. NET and C. View All. Fields and Properties in C. C Curator Updated date Dec 05, The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer. Next Recommended Reading.
Windows 10 Vs Windows Visual Studio Vs Visual Studio Understanding Matplotlib With Examples. Understanding Numpy With Examples. Fields are used for data hiding, which is a best practice for Object Oriented Design:. In computer science, information hiding is the principle of segregation of the design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decision is changed.
The protection involves providing a stable interface which protects the remainder of the program from the implementation the details that are most likely to change. Wikipedia Definition. While in the code example above it looks like pointless ceremony but if you wanted to perform operations on the name, such as making it title case this would be a great place to do it. Clearly both will expose an object's state to the outside world.
Object orientated programming principles say that the data is hidden and safe from accidental alteration. Data hiding is the key term describing an Object Oriented Language. That means the internal working of a class should be hidden from the outside world. So, If you expose a member field you are actually exposing the internal implementation of the class. Therefore we wrap fields with Properties to give us the ability to change the implementation without breaking code depending on us.
The above statements underlines that properties should be used to define a class's public interface while fields are meant to be used in the private, internal workings of a class. A field is a variable that is declared directly in a class or struct.
Generally, developers should use fields only for variables that have private or protected accessibility.
0コメント