Search⌘ K
AI Features

Storing Data Within Fields

Explore how to store data within class fields by defining public fields for a person’s name and date of birth. Understand choosing appropriate data types like DateOnly, DateTimeOffset, and handling nullability. Learn about access modifiers and how to set and output field values using C#, enhancing your object-oriented programming skills.

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 ...

C#
public class Person : object
{
// fields
public string? Name;
public DateTime DateOfBirth;
}

Data

...