Enumerated types and state machines#
You can create our own types in C#. An example is enum.
If a variable can only have a specific number of values, then an enum is useful.
- enumerated type
a data type consisting of a set of named values called enumerators of the type. The enumerator names are usually identifiers that behave as constants.
Example:
var machines = new List<IndustrialMachine>
{
new("CNC-Lathe-01", MachineStatus.Running, Priority.Low),
new("Hydraulic-Press-02", MachineStatus.Warning, Priority.Medium),
new("Conveyor-Belt-03", MachineStatus.Error, Priority.Critical),
new("Welding-Robot-04", MachineStatus.Maintenance, Priority.High, MaintenanceType.Preventive)
};
// Status-based operations
foreach (var machine in machines)
{
var statusMessage = machine.Status switch
{
MachineStatus.Running => "â
Operating normally",
MachineStatus.Warning => "â ī¸ Requires attention",
MachineStatus.Error => "â Production stopped",
MachineStatus.Maintenance => $"đ§ Under {machine.ScheduledMaintenance} maintenance",
MachineStatus.Starting => "đ Starting up...",
MachineStatus.Stopped => "âšī¸ Offline",
_ => "Unknown status"
};
Console.WriteLine($"{machine.Name}: {statusMessage} (Priority: {machine.AlertLevel})");
}
internal enum MachineStatus
{
Stopped,
Starting,
Running,
Warning,
Error,
Maintenance
}
internal enum MaintenanceType
{
Preventive,
Corrective,
Emergency,
Calibration
}
internal enum Priority
{
Low = 1,
Medium = 2,
High = 3,
Critical = 4
}
internal record IndustrialMachine(
string Name,
MachineStatus Status,
Priority AlertLevel,
MaintenanceType? ScheduledMaintenance = null
);
(Example generated with GitLab Duo. Slightly modified)
Output:
CNC-Lathe-01: â
Operating normally (Priority: Low)
Hydraulic-Press-02: â ī¸ Requires attention (Priority: Medium)
Conveyor-Belt-03: â Production stopped (Priority: Critical)
Welding-Robot-04: đ§ Under Preventive maintenance (Priority: High)
State machines are often implemented using enumerated types. A state machine can also be used to model the behavior of a robot.
Activity 28 (Coffee machine state machine)
Implement the following state machine for a coffee machine using a console program. Use an enum for the states. Simulate the states using console messages like brewing.
Steps:
define an enumerated type
define a variable with this type
create an endless loop
use an
if-elsestatement to differentiate between the actions.An action can be, e.g., wait (use
Task.Delay(milliseconds)) or change state.
stateDiagram-v2
[*] --> IDLE
IDLE --> BREWING: "s" pressed
BREWING --> DONE: after 2s
DONE --> IDLE: "r" pressed
DONE --> [*]: "e" pressed