1.2.8 Translating UML Classes Into C#

Video: Class Diagrams and Corresponding Code (6:06)
Translate Structure Before Behavior

A UML class diagram can describe:

  • class names;
  • fields;
  • field types;
  • access visibility;
  • relationships.

At this point, translate those structural parts into C#.

Do not add methods, constructors, or properties unless the current diagram and course boundary require them.

Start with the Class Name

UML:

Player

C#:

class Player
{
}
Translate Fields and Types

UML:

Player
--------------------------------
name : string
jerseyNumber : int
team : Team

C# can become:

class Player
{
    public string name;
    public int jerseyNumber;
    public Team team;
}

Use the exact visibility, names, and types required by the current design.

Translate Related Classes Separately

For:

Team
-------------------------
name : string

create the corresponding Team class:

class Team
{
    public string name;
}

The Team field in Player now refers to that custom type.

Do Not Confuse Class Relationships with Runtime Relationships

The class definition:

public Team team;

makes a Team reference possible.

The runtime assignment:

player1.team = team1;

connects two specific objects.

Class design and object state are related but different.

Build and Read Compiler Evidence

After translating a focused part of the UML:

  1. save;
  2. build;
  3. read current diagnostics;
  4. correct only evidence-supported differences.

The UML is the design reference.

The compiler tells you whether the C# source is valid.

Both are needed.