Enumerations
Explore how to create and utilize enumerations in C#, enabling you to represent groups of related constants with type safety. Understand how enumerations improve code clarity and safeguard against invalid values while integrating with methods and control flow structures like switch statements.
We'll cover the following...
C# allows us to create enumerations in addition to primitive data types. An enumeration represents a collection of logically related constants.
Suppose a method needs to accept a day of the week as a parameter. We have several options:
We could accept a string value (like
"Monday").We could accept an integer that represents the day of the week (like
2).We could use enumerations.
Enumerations definition
We can create an enumeration containing all days of the week to ensure the caller selects a valid, predefined constant.
An enumeration is declared using the enum keyword:
enum WeekDay{}
Line 1: Uses the
enumkeyword to define a new type namedWeekDay.
We can ...