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
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.
public class Person{private int age;private string name; // declaration of fields}
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:
using System;public class Person{private int age; // Field "age" declaredprivate string name; // Field "name" declaredpublic int Age{ // Property for age used inside the classget{ // getter to get the person's agereturn age;}set{ // setter to set the person's ageage = value;}}public string Name{ // Property for name used inside the classget{ // getter to get the person's namereturn name;}set{ // setter to set the person's namename = value;}}}public class Program{public static void Main(){Person p1 = new Person();p1.Age = 25; // setting the age. Note that Property "Age"// is used and not the field "age" as it is privateConsole.WriteLine("Person Age is : {0}", p1.Age); // printing person's agep1.Name = "Bob";Console.WriteLine("Person Name is: {0}", p1.Name); // printing person's name}}
Line 2: We declare a class named Person
.
Lines 3–5: We declare two fields named age
and name
. We mostly declare the fields privately.
Lines 7–30: We define the properties Age
and Name
that contain the setters and getters to read and write the age
(field) and name
(field), respectively.
Line 37: We declare an instance p1
of the defined class.
Lines 39 and 44: The property Age
and Name
sets the value for the field age
and name
respectively.
Lines 42 and 46: The property Age
and Name
gets and prints the value of the field age
and name
respectively.
Free Resources