Storing Data Within Fields

Learn about defining fields and storing data with a step-by-step guide to field declaration and initialization in C#.

We’ll now define a selection of fields in the class to store information about a person.

Defining fields

Let’s say we have decided that a person is composed of a name and a date of birth. We will encapsulate these two values inside a person, and the values will be visible outside it:

  • Inside the Person class, write statements to declare two public fields for storing a person’s name and date of birth, as highlighted in the following code:

Press + to interact
public class Person : object
{
// fields
public string? Name;
public DateTime DateOfBirth;
}

Data type for DateOfBirth field

We have multiple choices for the data type of the DateOfBirth field. .NET 6 introduced the DateOnly type. This would store only the date without a time value. DateTime stores the date and time of when the person was born. An ...