# 6.การแปลงข้อมูล

หลังจากที่เราได้ลองสร้างตัวแปรพร้อมกำหนดค่ากันไปละ คราวนี้ถ้าเกิดว่าเราอยากจะส่งข้อมูลที่ต่างชนิดไปให้กับตัวแปรต่างๆดูบ้างละเราจะทำยังไง? แมวน้ำทั้งหลายเจ้าจงลองดูวีดีโอการแปลงข้อมูลด้านล่างนี้โดยพลัน

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

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

### 👨‍🚀 การแปลงข้อมูลแบบอัตโนมัติ (Implicit conversions)

เราไม่ต้องทำอะไรเลย เพราะโปรแกรมจะจัดการให้อัตโนมัติ เช่น เราสามารถแปลง int เป็น double ได้ตามตัวอย่างด้านล่างเบย

```
int a = 3;
double b = a;
```

### 👨‍🚀 การแปลงข้อมูลด้วยตัวเอง (Explicit conversion)

กรณีที่โปรแกรมจัดการให้เราอัตโนมัติไม่ได้ เราจะต้องทำการระบุ data type ที่จะทำการแปลงลงไปด้วย หรือเรียกว่าการ **cast** เช่น เราทำการแปลง double เป็น int แบบตัวอย่างด้างล่างงุย

```csharp
double a = 3.33;
int b = (int)a;
```

{% hint style="warning" %}
**ข้อควรระวังในการทำ Explicit conversion**

* ในบางทีการแปลงข้อมูลอาจจะทำให้ข้อมูลบางอย่างหายไปได้ เช่นในตัวอย่าง มันจะตัดทศนิยมออกไป ดังนั้น b จะมีค่าเป็น 3
* ถ้ามันไม่สามารถแปลงได้ โปรแกรมจะพังทันที (เราเรียกกรณีนี้ว่าเกิด exception)
  {% endhint %}

### 👨‍🚀 การแปลงโดยใช้ตัวช่วย

1.ตัวช่วยในการแปลงข้อมูลเรานิยมใน **System.Convert** ตามตารางด้านล่าง

| คำสั่ง                        | ความหมาย                      |
| ----------------------------- | ----------------------------- |
| System.Convert.ToInt32( x );  | แปลง x ให้กลายเป็น **int**    |
| System.Convert.ToDouble( x ); | แปลง x ให้กลายเป็น **double** |
| System.Convert.ToString( x ); | แปลง x ให้กลายเป็น **string** |

&#x20;2.การแปลงข้อมูลจาก string เป็น data type ที่ระบุโดยใช้ตัวช่วย

```csharp
int a = int.Parse("1");
double b = int.Parse("3.33");
```

### 👨‍🚀 การแปลงข้อมูลเป็น string

เรานิยมใช้คำสั่ง **.ToString()** ต่อท้าย เพื่อทำการแปลงข้อมูลนั้นๆให้กลายเป็น string ตามตัวอย่างด้านล่าง

```csharp
int a = 3;
string b = a.ToString();
string c = 3.33.ToString();
strubg d = "Hello".ToString();
```


---

# 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/basic/type-conversions.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.
