Giới thiệu
Phương thức bool.Parse() chuyển đổi chuỗi "true" hoặc "false" (không phân biệt chữ hoa/thường) thành giá trị boolean. Ném FormatException nếu chuỗi không hợp lệ.
Ví dụ cơ bản
string str = "false"; bool res = bool.Parse(str); // false
Ví dụ hoàn chỉnh
using System;
class Demo
{
static void Main()
{
string str = "false";
bool res = bool.Parse(str);
Console.WriteLine(res);
}
}
Kết quả
False
Các chuỗi hợp lệ
"true","True","TRUE"->true"false","False","FALSE"->false
Phương thức an toàn: bool.TryParse()
string input = "True";
if (bool.TryParse(input, out bool result))
{
Console.WriteLine($"Giá trị: {result}");
}
else
{
Console.WriteLine("Không phải boolean hợp lệ.");
}
Lưu ý quan trọng
- Chỉ chấp nhận "true"/"false", không chấp nhận "1"/"0", "yes"/"no", v.v.
- Phân biệt chữ hoa/thường: không (case-insensitive).
- Ném
ArgumentNullExceptionnếu chuỗi là null. - Để parse "1"/"0", dùng
Convert.ToBoolean()hoặc logic tùy chỉnh.
Ví dụ Convert.ToBoolean
Convert.ToBoolean("1"); // true
Convert.ToBoolean("0"); // false
Convert.ToBoolean("true"); // true
Convert.ToBoolean(null); // false (không ném ngoại lệ)