Field vs Property
Properties | Fields |
Can assign values and receive data. | Contains data only. |
Cannot be used with 2 keywords ref and out. | As a variable, it can be used with ref and out. |
Defined by two expressions get and set. | There are no two expressions get and set |
Contains actions to handle the field. | Unable to manage data import/export. |
Usually public. | Usually kept private, all data access operations are through properties. |
In C#, a field is a variable (that can be of any type) that is defined inside a class. It can be used to define the characteristics of an object or a class.
On the other hand, a property is a member of the class that provides an abstraction to set (write) and get (read) the value of a private field.
Fields
Fields, as mentioned above, are variables defined in a class. Mostly, they are declared as a private variable, otherwise, the purpose of encapsulation and abstraction would be compromised.
Properties
Properties are also called accessor methods and are declared publicly inside the class. They cannot be implemented alone. They require the declaration of fields before so that they can then read or write them accordingly.
The following shows the program with properties being used:
Explanation
Line 2: We declare a class named
Person
.Lines 3–5: We declare two fields named
age
andname
. We mostly declare the fields privately.Lines 7–30: We define the properties
Age
andName
that contain the setters and getters to read and write theage
(field) andname
(field), respectively.Line 37: We declare an instance
p1
of the defined class.Lines 39 and 44: The property
Age
andName
sets the value for the fieldage
andname
respectively.Lines 42 and 46: The property
Age
andName
gets and prints the value of the fieldage
andname
respectively.
Last updated