1.2.6 Classes as Custom Types

Video: Classes, Abstractions of Objects (8:34)
A Class Creates a Type for the Program

C# already provides basic types such as:

int
double
bool
stringdouble
bool
string

A class lets a programmer define a custom type that represents a concept needed by the application.

For a soccer program, useful custom types might include:

Object diagram showing Player custom type, then player1 reference name, then new Player() object creation.
PlayerCustomType.
  • New
  • Changed
  • Removed
One Type Can Produce Many Instances
Player player1 = new Player();
Player player2 = new Player();

Both objects share the same custom type.

Their field values can differ.

A class lets the program define common structure once and reuse it across many instances.

Custom Types Make Code Match the Domain

Compare:

string value1;
string value2;

with:

Player player1;
Team team1;

The custom types communicate more about the roles of the values.

They make the program's structure easier to relate to the system being modeled.

UML Class Diagrams Also Use Type Thinking

A UML class box named:

Player

represents the custom type.

An object diagram header:

player1 : Player

means that player1 is an instance of that type.

The same type concept connects UML and C#.