Skip to content

Commit a66190f

Browse files
authored
Merge pull request #49712 from wwlpublish/882fb6eb904537ee56fa040133256c81cb1967f9cd5ae798fd376de9b62a7fff-live
Modules/M03-implement-enum-struct-record-types
2 parents 441c250 + b3b8580 commit a66190f

16 files changed

+575
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
### YamlMime:ModuleUnit
2+
uid: learn.wwl.implement-enum-struct-record-types.introduction
3+
title: Introduction
4+
metadata:
5+
title: Introduction
6+
description: "Introduction to the module."
7+
ms.date: 03/29/2025
8+
author: wwlpublish
9+
ms.author: eric
10+
ms.topic: unit
11+
durationInMinutes: 1
12+
content: |
13+
[!include[](includes/1-introduction.md)]
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
### YamlMime:ModuleUnit
2+
uid: learn.wwl.implement-enum-struct-record-types.use-enums-represent-named-constants-csharp
3+
title: Use enums to represent named constants in C#
4+
metadata:
5+
title: Use enums to represent named constants in C#
6+
description: "Learn how to use enums in C# to define named constants and improve code readability."
7+
ms.date: 03/29/2025
8+
author: wwlpublish
9+
ms.author: eric
10+
ms.topic: unit
11+
durationInMinutes: 6
12+
content: |
13+
[!include[](includes/2-use-enums-represent-named-constants-csharp.md)]
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
### YamlMime:ModuleUnit
2+
uid: learn.wwl.implement-enum-struct-record-types.create-structs-encapsulate-data-csharp
3+
title: Create encapsulated data with structs in C#
4+
metadata:
5+
title: Create encapsulated data with structs in C#
6+
description: "Learn how to use structs in C# to group related data into lightweight, efficient containers."
7+
ms.date: 03/29/2025
8+
author: wwlpublish
9+
ms.author: eric
10+
ms.topic: unit
11+
durationInMinutes: 7
12+
content: |
13+
[!include[](includes/3-create-structs-encapsulate-data-csharp.md)]
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
### YamlMime:ModuleUnit
2+
uid: learn.wwl.implement-enum-struct-record-types.apply-records-immutable-data-models-csharp
3+
title: Apply records for immutable data models in C#
4+
metadata:
5+
title: Apply records for immutable data models in C#
6+
description: "Learn how to use records in C# to create immutable data models with value-based equality."
7+
ms.date: 03/29/2025
8+
author: wwlpublish
9+
ms.author: eric
10+
ms.topic: unit
11+
durationInMinutes: 8
12+
content: |
13+
[!include[](includes/4-apply-records-immutable-data-models-csharp.md)]
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
### YamlMime:ModuleUnit
2+
uid: learn.wwl.implement-enum-struct-record-types.exercise-implement-enum-struct-record-types
3+
title: Exercise - Implement enum, struct, and record types
4+
metadata:
5+
title: Exercise - Implement enum, struct, and record types
6+
description: "Practice implementing enums, structs, and records in C# to reinforce your understanding of these concepts."
7+
ms.date: 03/29/2025
8+
author: wwlpublish
9+
ms.author: eric
10+
ms.topic: unit
11+
durationInMinutes: 25
12+
content: |
13+
[!include[](includes/5-exercise-implement-enum-struct-record-types.md)]
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
### YamlMime:ModuleUnit
2+
uid: learn.wwl.implement-enum-struct-record-types.knowledge-check
3+
title: Knowledge check
4+
metadata:
5+
title: Knowledge check
6+
description: "Check what you've learned in this module."
7+
ms.date: 03/29/2025
8+
author: wwlpublish
9+
ms.author: eric
10+
ms.topic: unit
11+
durationInMinutes: 3
12+
content: |
13+
[!include[](includes/6-knowledge-check.md)]
14+
quiz:
15+
title: "Check your knowledge"
16+
questions:
17+
- content: "What is the primary purpose of using enums in C#?"
18+
choices:
19+
- content: "To define a set of named constants for fixed values."
20+
isCorrect: true
21+
explanation: "Correct. Enums are used to represent a set of predefined values with meaningful names, improving code readability and maintainability."
22+
- content: "To store multiple values in a single variable."
23+
isCorrect: false
24+
explanation: "Incorrect. Enums don't store multiple values; they represent a single value from a predefined set of constants."
25+
- content: "To perform mathematical operations on integral types."
26+
isCorrect: false
27+
explanation: "Incorrect. Enums aren't designed for mathematical operations but for representing fixed sets of values."
28+
- content: "What keyword is used to define a struct in C#?"
29+
choices:
30+
- content: "Struct"
31+
isCorrect: true
32+
explanation: "Correct. The 'struct' keyword is used to define a struct in C#. It allows creating a value type that encapsulates related data."
33+
- content: "Class"
34+
isCorrect: false
35+
explanation: "Incorrect. The 'class' keyword is used to define reference types, not value types like structs."
36+
- content: "Interface"
37+
isCorrect: false
38+
explanation: "Incorrect. The 'interface' keyword is used to define contracts for classes or structs, not the struct itself."
39+
- content: "What is the primary advantage of using records in C# for data modeling?"
40+
choices:
41+
- content: "They allow for mutable properties by default."
42+
isCorrect: false
43+
explanation: "Incorrect. Records are immutable by default, which is one of their key advantages for data integrity."
44+
- content: "They support complex behavior-focused operations."
45+
isCorrect: false
46+
explanation: "Incorrect. Records are designed for simple, immutable data models rather than complex behavior-focused operations."
47+
- content: "They provide value-based equality and immutability."
48+
isCorrect: true
49+
explanation: "Correct. Records offer value-based equality and immutability, making them ideal for scenarios where data shouldn't change after creation."
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
### YamlMime:ModuleUnit
2+
uid: learn.wwl.implement-enum-struct-record-types.summary
3+
title: Summary
4+
metadata:
5+
title: Summary
6+
description: "Summarize the key concepts covered in this module."
7+
ms.date: 03/29/2025
8+
author: wwlpublish
9+
ms.author: eric
10+
ms.topic: unit
11+
durationInMinutes: 1
12+
content: |
13+
[!include[](includes/7-summary.md)]
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
C# offers powerful tools like enums, structs, and records. These tools help developers write clean, maintainable, and efficient code by organizing data and improving readability.
2+
3+
Imagine you're a developer on an e-commerce platform. Order statuses like 'Pending' or 'Shipped' need to be managed in a way that prevents mistakes. The statuses need to group customer details like name and address into a compact structure, and handle API responses with data that can't be changed. With the right tools, your code can avoid clutter and becoming error-prone. Enums, structs, and records in C# help you organize data, ensure reliability, and make your code easier to maintain.
4+
5+
## Learning objectives
6+
7+
- Use enums in C# to define named constants and prevent invalid values.
8+
- Work with structs in C# to encapsulate related data into lightweight containers.
9+
- Create records in C# to model immutable data and ensure consistency.
10+
11+
## Prerequisites
12+
13+
- Visual Studio Code installed with the C# Dev Kit.
14+
- Basic knowledge of the Visual Studio Code IDE.
15+
- Basic understanding of the C# programming language.
16+
- Familiar with classes, abstract classes, interfaces and inheritance.
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
Imagine working on a project to track order statuses, and you need to organize values like "Pending," "Shipped," or "Delivered" in a clear and manageable way. Using enums in C# lets you create a list of these order statuses. The use of enums makes it easier to use these statuses in your project without recreating or searching for them repeatedly.
2+
3+
## Describe a scenario for enums and the value of enums
4+
5+
Enums are ideal for representing a set of predefined values that are mutually exclusive or can be combined. For example, you might use an enum to define the seasons of the year:
6+
7+
```csharp
8+
enum Season
9+
{
10+
Spring,
11+
Summer,
12+
Autumn,
13+
Winter
14+
}
15+
```
16+
17+
*Code sample demonstrates how to define an enum to represent mutually exclusive values.*
18+
19+
Enums improve code readability by replacing numeric literals with meaningful names. They also help prevent invalid values from being assigned, as only the defined constants are allowed.
20+
21+
> [!NOTE]
22+
> Enums can also represent combinations of choices using bit flags, which are useful for scenarios like file permissions or configuration options.
23+
24+
## Define enums
25+
26+
To define an enum in C#, use the `enum` keyword followed by the name of the enum and its members. Here’s an example of a simple enum for the days of the week:
27+
28+
```csharp
29+
enum DaysOfWeek
30+
{
31+
Sunday,
32+
Monday,
33+
Tuesday,
34+
Wednesday,
35+
Thursday,
36+
Friday,
37+
Saturday
38+
}
39+
```
40+
41+
*Code sample demonstrates how to define an enum for the days of the week.*
42+
43+
By default, the underlying type of an enum is `int`, and the values start at 0, incrementing by 1 for each member.
44+
45+
> [!NOTE]
46+
> Enums are limited to integral types (for example, `int`, `byte`, `short`) and can't represent non-integral values like strings or decimals.
47+
48+
## Set underlying types and values for enums
49+
50+
You can specify a different underlying integral type for an enum and assign custom values to its members. For example:
51+
52+
```csharp
53+
enum ErrorCode : ushort
54+
{
55+
None = 0,
56+
Unknown = 1,
57+
ConnectionLost = 100,
58+
OutlierReading = 200
59+
}
60+
```
61+
62+
*Code sample demonstrates how to set a custom underlying type and values for an enum.*
63+
64+
This flexibility allows you to align enum values with external systems or specific requirements.
65+
66+
> [!TIP]
67+
> Avoid using non-integral types like `char` as the underlying type for enums, which can lead to unreliable behavior.
68+
69+
## Perform conversions with enums
70+
71+
Enums support explicit conversions between their members and the underlying integral type. For example:
72+
73+
```csharp
74+
DaysOfWeek day = (DaysOfWeek)3;
75+
Console.WriteLine(day); // Outputs: Wednesday
76+
```
77+
78+
*Code sample demonstrates how to perform an explicit conversion from an integral value to an enum.*
79+
80+
You can validate enum values using the `System.Enum.IsDefined` method:
81+
82+
```csharp
83+
bool isValid = Enum.IsDefined(typeof(DaysOfWeek), 3);
84+
Console.WriteLine(isValid); // Outputs: True
85+
```
86+
87+
*Code sample demonstrates how to validate an enum value using `System.Enum.IsDefined`.*
88+
89+
> [!TIP]
90+
> If the value is invalid, you can handle it by assigning a default value or throwing an exception to ensure safe usage.
91+
92+
## Apply best practices for designing enums
93+
94+
To design enums effectively:
95+
96+
- Use singular nouns for simple enums and plural nouns for flag enums.
97+
- Provide a value of zero for simple enums, typically named `None`.
98+
- Avoid using special or reserved values, as they can confuse users.
99+
- Use powers of two for flag enums to enable bitwise operations.
100+
101+
> [!TIP]
102+
> Consider adding extension methods to enums for more functionality, such as validation or formatting.
103+
104+
## Implement enums with custom values and methods
105+
106+
While enums can't contain methods directly, you can add functionality using extension methods. For example:
107+
108+
```csharp
109+
public static class DaysOfWeekExtensions
110+
{
111+
public static bool IsWeekend(this DaysOfWeek day)
112+
{
113+
return day == DaysOfWeek.Saturday || day == DaysOfWeek.Sunday;
114+
}
115+
}
116+
117+
DaysOfWeek today = DaysOfWeek.Saturday;
118+
Console.WriteLine(today.IsWeekend()); // Outputs: True
119+
```
120+
121+
*Code sample demonstrates how to use an extension method to add functionality to an enum.*
122+
123+
> [!TIP]
124+
> Use extension methods to enhance enums without modifying their definition, making them more versatile and reusable.
125+
126+
## Use object initializers with structs
127+
128+
Define a struct with properties to group related data together and make it easier to initialize and work with instances of the struct.
129+
130+
```csharp
131+
public struct Point
132+
{
133+
public int X { get; set; }
134+
public int Y { get; set; }
135+
}
136+
```
137+
138+
Using an object initializer, you can create and initialize a `Point` instance like this:
139+
140+
```csharp
141+
var point = new Point { X = 10, Y = 20 };
142+
```
143+
144+
*Code sample demonstrates how to use an object initializer to set property values when creating a struct instance.*
145+
146+
> [!NOTE]
147+
> Object initializers make your code more concise and easier to read, especially when working with structs that have multiple properties.
148+
149+
Enums in C# simplify code by allowing you to define a set of named constants, making it easier to represent and manage fixed values like statuses or categories while improving readability and maintainability.

0 commit comments

Comments
 (0)