# 27.Enum

💬 เคยมีปัญหาเวลาที่จะกำหนดค่าของที่มันเป็นข้อมูลเซ็ตเดิมๆกันไหม เช่นกำหนดว่าวันนี้เป็นวันอะไร จันทร์ อังคาร พุธ... ซึ่งอีกหน้านึงก็ต้องกำหนดค่าวัน จันทร์ อังคาร พุธ ... อีกไรงี้ ในรอบนี้เราจะมาดูการสร้างสิ่งที่เรียกว่า **Enum** กันดูบ้างนะว่ามันจะมาช่วยเราเรื่องนี้ยังไง

{% embed url="<https://www.youtube.com/watch?v=c2D7RLo_OeY&list=PLUjAn8nwWnijERZ3HpzBk7NfSrau74_lQ&index=45>" %}

## 🎯 สรุปสั้นๆ

### 👨‍🚀 Enum คือ

เซ็ตของข้อมูลที่เราสร้างขึ้น โดยเบื้องหลังมันจะเก็บข้อมูลในรูปแบบของตัวเลข และเราสามารถกำหนดค่าให้มันได้ว่ามันจะมีค่าเป็นเลขอะไร แต่ถ้าเราไม่กำหนดค่ามันจะไล่เลขให้อัตโนมัติจากบนลงล่าง เริ่มจาก 0

ตัวอย่างการสร้างเซ็ตข้อมูลของวันในสัปดาห์

```csharp
public enum DaysOfWeek
{
    Sunday = 0,
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
}
```

ตัวอย่างการแปลง enum เป็นตัวเลข

```csharp
int day = (int)DaysOfWeek.Sunday;
```

ตัวอย่างการแปลงตัวเลขกลับไปเป็น enum

```csharp
DaysOfWeek today = (DaysOfWeek)3;
```

{% hint style="info" %}
ถ้าเราใส่ตัวเลขที่ไม่มีอยู่ในเซ็ตของ enum เราจะได้เลขนั้นๆออกมาแทน
{% endhint %}

### 👨‍🚀 การแปลง string เป็น Enum

เราสามารถแปลง string ไปเป็น enum ได้ด้วยการใช้ Enum.Parse() หรือ Enum.TryParse() ครับตามตัวอย่างด้านบน

```csharp
var today = Enum.Parse<DayOfWeek>("Sunday");
```

{% hint style="warning" %}
**Enum.Parse()**\
ถ้า string ตัวนั้นไม่ตรงกับข้อมูลในเซ็ตนั้นเลย มันจะเกิด error ออกมา ดังนั้นผมแนะนำว่าควรจะใช้ **Enum.TryParse()** มากกว่าครับ
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.saladpuk.com/beginner-1/csharp101/intermediate/enum.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
