A field belongs to an object.
An assignment gives that field a value.
For example:
player1.jerseyNumber = 7;Read it as:
The assignment changes one part of the object's current state.
Consider:
player1.name = "Jordan";The left side identifies where the value will be stored:
player1.nameThe right side supplies the value:
"Jordan"A helpful reading is:
In this context:
=means assignment.
For example:
player1.isAvailable = true;means:
Do not read the statement as a mathematical equation.
The source is telling the program to change state.
Suppose the supplied Player class contains:
string name;
int jerseyNumber;
bool isAvailable;Appropriate assignments include:
player1.name = "Jordan";
player1.jerseyNumber = 7;
player1.isAvailable = true;The values match the field types:
If a value does not match the expected type, the compiler can report a problem.
Suppose the UML object is:
player1 : Player
-------------------------
name = "Jordan"
jerseyNumber = 7
isAvailable = trueA matching C# sequence can be:
Player player1 = new Player();
player1.name = "Jordan";
player1.jerseyNumber = 7;
player1.isAvailable = true;The UML shows the desired snapshot.
The assignments create that state during execution.
Consider:
player1.jerseyNumber = 7;
player1.jerseyNumber = 9;After both statements execute, the field contains the later assigned value:
9The second assignment replaces the earlier field value.
This does not create another Player object.
It changes the state of the same object.
If:
int jerseyNumber;then changing:
player1.jerseyNumber = 7;to:
player1.jerseyNumber = 9;changes the value.
The field is still an int.
Type and value are different parts of the object's structure.
Suppose the UML says:
player1 : Player
name = "Jordan"
player2 : Player
name = "Casey"Then:
player1.name = "Jordan";
player2.name = "Casey";preserves the intended mapping.
This code:
player1.name = "Casey";
player2.name = "Jordan";uses valid strings and valid fields.
It still represents the wrong model.
Correct assignment includes:
A supplied class may contain more fields than the current object diagram displays.
If the current model does not specify a value for one of those fields, do not invent a value merely to fill the object.
The current requirement and UML control the intended state.
Place execution before a field assignment.
Inspect the object.
Then use F10 to execute the statement.
Inspect the field again.
Conceptually:
before assignment
jerseyNumber = current value
execute:
player1.jerseyNumber = 7;
after assignment
jerseyNumber = 7This makes field assignment visible as a runtime state change.
Keep this structure in mind:
objectReference.field = value;Read it as:
That pattern will remain useful as objects become connected to other objects in CO-029.