เมธอด Char.TryParse() ใน C# แปลงสตริงที่ระบุให้เป็นอักขระ Unicode เทียบเท่า คืนค่า Boolean บอกสำเร็จ/ล้มเหลว
ไวยากรณ์
public static bool TryParse(string str, out char res);
ตัวอย่างที่ 1: แปลงไม่สำเร็จ (สตริงยาวเกิน 1 ตัว)
using System;
public class Demo
{
public static void Main()
{
bool res;
char ch;
res = Char.TryParse("10", out ch);
Console.WriteLine(res);
Console.WriteLine(ch.ToString());
}
}
ผลลัพธ์
False
ตัวอย่างที่ 2: แปลงสำเร็จ
using System;
public class Demo
{
public static void Main()
{
bool res;
char ch;
res = Char.TryParse("P", out ch);
Console.WriteLine(res);
Console.WriteLine(ch.ToString());
}
}
ผลลัพธ์
True
P
ข้อดีของ TryParse: ไม่โยน Exception เมื่อแปลงไม่ได้ ใช้ตรวจสอบได้ด้วยค่าคืน Boolean เหมาะสำหรับ Validate Input