1.2.8 Assigning Values to Compatible Types

The Left Side and Right Side of an Assignment Must Make Sense Together

C# uses type information to determine whether a value can be stored in a field.

For example:

C#
int jerseyNumber;
bool isAvailable;
string name;

Compatible assignments include:

C#
jerseyNumber = 7;
isAvailable = true;
name = "Jordan";

Each value fits the type of the destination.

Quotation Marks Change the Kind of Value

Compare:

C#
7

with:

C#
"7"

The first is numeric.

The second is text.

If the field is an int, the numeric value is the natural match.

Likewise:

C#
true

is Boolean, while:

C#
"true"

is text.

Object References Also Have Types

If a field is:

C#
Team team;

then a compatible assignment can be:

C#
team = team1;

when team1 refers to a Team object.

Text such as:

C#
team = "Wildcats";

does not represent the same kind of information.

Let the Declared Type Guide You

When an assignment fails, inspect:

  1. the destination type;
  2. the value type;
  3. the requirement.

Do not change the field type merely to make one incorrect value compile.

The type is part of the class design.