1.2.13 Assigning Values to Compatible Types

Video: Type Compatibility (9:49)
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:

int jerseyNumber;
bool isAvailable;
string name;

Compatible assignments include:

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

Each value fits the type of the destination.

Quotation Marks Change the Kind of Value

Compare:

7

with:

"7"

The first is numeric.

The second is text.

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

Likewise:

true

is Boolean, while:

"true"

is text.

Object References Also Have Types

If a field is:

Team team;

then a compatible assignment can be:

team = team1;

when team1 refers to a Team object.

Text such as:

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.