What is the difference between field and property?

Almost every student or developer has learned OOPObject-oriented programming, where most have come across the concepts of variable and property. These concepts also exist in C#, which is a modern programming language built on the .Net framework.

In this Answer, we'll emphasize the substantial difference between two terms in C#: field and property. But before that, let's look at the basic definition of field and property terminologies.

What are fields in C#?

We all know that every object has some characteristics and specific behaviors. To represent those characteristics, we use distinct fields in C#.

Code example

There is a public class employee. It contains different types of fields including Unique_id, first_Name, and last_Name.

// employee class
public class employee{
// class attributes
private int Unique_id;
private string first_Name;
private string last_Name;
}
  • Line 2: We import the employee class, which contains three private fields.
  • Line 4: We initialize a private integer member variable, Unique_id.
  • Line 5–6: We initialize private string member variables for first and last name.

What are properties in C#?

A property is primarily a member that provides a particular method, process, or mechanism through which we can access, read, or write into a private field.

Code example

// employee class
public class employee {
// class fields or attributes
private int Unique_id;
private string first_Name;
private string last_Name;
// class functions or methods
public int id { get { return Unique_id; } set { _id = val; } }
public string first_Name { get { return first_Name; } set { first_Name = val; } }
public string last_Name { get { return last_Name; } set { last_Name = val; } }
}
  • Line 4–6: We initialize the fields of the employee class.
  • Line 8: Here, we have the unique id property to get and set the integer's unique identifier.
  • Line 9: We use the first_name property to get and set first names.
  • Line 10: We use the last_name property to get and set last names.

Field vs. Property

Field

Property

These are variables declared in the class and have no restriction on data types.

It is a member of that class, through which we can read or write in the private fields.

It shows the characteristics of the class or an object.

These are used to make inputs and receive outputs from the fields. These are commonly known as getter and setter functions.

Free Resources