1.2.11 Defining Fields

A Field Declaration Defines Stored Information for a Class

Inside a class, a field declaration tells C#:

Example:

C#
public int jerseyNumber;

Read it as:

Player objects have an accessible field named jerseyNumber whose type is int.

Declare Fields Inside the Class Body

A simple class can contain:

C#
class Player
{
    public string name;
    public int jerseyNumber;
    public bool isAvailable;
}

The fields belong to Player objects because they are declared inside the Player class.

Field Declarations Are Not Assignments

This:

C#
public int jerseyNumber;

defines a field.

This:

C#
player1.jerseyNumber = 7;

assigns a value to the field on one object.

Definition and runtime assignment are separate steps.

Use Types that Match the Model

If the class diagram shows:

Plain text
jerseyNumber : int

declare:

C#
public int jerseyNumber;

If it shows:

Plain text
isAvailable : bool

declare a compatible Boolean field.

A Class-Type Field Creates a Place for an Object Reference

For:

Plain text
team : Team

a C# field can be:

C#
public Team team;

That field can later refer to a Team object.

Declaring the field does not create the Team automatically.