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 above code section we define property as public and field 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.
Another important difference is that interfaces can have properties but not fields.
Using property we can throw an event but this is not possible in field.
Code Snippet:
public class Career
{
// field
// field
private int _path;
// Path is Property
// Path is Property
public int Path
{
get
{
return _path;
}
set
{
_path = value;
}
}
}
No comments:
Post a Comment