Fields are normal variable members of a class. Generally, you should declare your fields as private, then use Properties to get and set their values. By this way you won’t affect their values them directly. This is common case practice since having public members violates the Encapsulation concept in OOP.
Object orientated programming principles say that the internal workings of a class should be hidden from the outside world. If you expose a field you're in essence exposing the internal implementation of the class. So we wrap the field using the property to hide the internal working of the class.
We can see that in the below code section we define property as public and filed as private, so user can only access the property but internally we are using the field, such that provides a level of abstraction and hides the field from user access.
Ex:
- public class Person
- {
- private int Id; //Field
- public int User_ID
- {
- //Property
- get
- {
- return Id;
- }
- set
- {
- Id = value;
- }
- }
- }
- public class Person
- {
- private int Id; //Field
- public int User_ID
- { //Property
- get
- {
- return Id;
- }
- set
- {
- valueChanged();
- Id = value;
- }
- }
- public void valueChanged()
- {
- //Write Code
- }
- }
Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site. For more info:- Xamarin App Development
ReplyDelete