What is the difference between fields and properties in C#?
Differences between fields and properties in C#
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
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.
Syntax
public class Person{private int age;private string name; // declaration of fields}
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:
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}}
Explanation
Line 2: We declare a class named
Person.Lines 3–5: We declare two fields named
ageandname. We mostly declare the fields privately.Lines 7–30: We define the properties
AgeandNamethat contain the setters and getters to read and write theage(field) andname(field), respectively.Line 37: We declare an instance
p1of the defined class.Lines 39 and 44: The property
AgeandNamesets the value for the fieldageandnamerespectively.Lines 42 and 46: The property
AgeandNamegets and prints the value of the fieldageandnamerespectively.
Free Resources