1.2.10 Defining Fields

Video: Defining Fields in C-Sharp Classes (12:45)
A Field Declaration Defines Stored Information for a Class

Inside a class, a field declaration tells C#:

  • the field's access level;
  • its type;
  • its name.

Example:

public int jerseyNumber;

Read it as:

Declare Fields Inside the Class Body

A simple class can contain:

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:

public int jerseyNumber;

defines a field.

This:

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:

jerseyNumber : int

declare:

public int jerseyNumber;

If it shows:

isAvailable : bool

declare a compatible Boolean field.

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

For:

team : Team

a C# field can be:

public Team team;

That field can later refer to a Team object.

Declaring the field does not create the Team automatically.