Để chuyển kiểu dữ liệu trong C#, dùng Type Conversion. Hai loại:
Chuyển đổi ngầm định (Implicit)
C# tự thực hiện an toàn kiểu. Ví dụ: kiểu số nhỏ -> lớn (int->long), derived class -> base class.
Chuyển đổi tường minh (Explicit)
Người dùng thực hiện qua hàm định nghĩa sẵn. Cần toán tử cast.
Ví dụ: Ép double sang int
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
double d = 8745.97;
int x;
x = (int)d;
Console.WriteLine(x); // 8745
Console.ReadKey();
}
}
}
Kết quả
8745