Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

So sánh int.Parse vs int.TryParse trong C#

Cả hai phương thức đều chuyển chuỗi sang int, nhưng xử lý lỗi hoàn toàn khác biệt. int.Parse ném exception, int.TryParse trả về bool.

int.Parse - Ném exception khi lỗi

string myStr = "120";
int res = int.Parse(myStr);  // 120
// Nếu myStr = "abc" → FormatException
// Nếu myStr = "9999999999" → OverflowException

int.TryParse - Trả về bool, không exception

string myStr = "120";
bool res = int.TryParse(myStr, out int a);  // res = true, a = 120
// Nếu myStr = "abc" → res = false, a = 0

Mã nguồn so sánh

using System.IO;
using System;

class Program
{
    static void Main()
    {
        // int.Parse
        int res1;
        string myStr1 = "120";
        res1 = int.Parse(myStr1);
        Console.WriteLine("Parse: " + res1);  // 120
        
        // int.TryParse
        bool res2;
        int a;
        string myStr2 = "120";
        res2 = int.TryParse(myStr2, out a);
        Console.WriteLine("TryParse: " + res2);  // True
    }
}

Kết quả

Parse: 120
TryParse: True

Quy tắc chọn

Tình huốngKhuyến nghịLý do
Input người dùng (form, console)TryParseKhông crash, dễ xử lý lỗi
Đọc file/configTryParseFile có thể hỏng/sai format
Dữ liệu nội bộ đã validateParseCode ngắn gọn, fail-fast
Hot path, performance criticalTryParseTránh exception overhead
Unit test expect exceptionParseKiểm tra exception được ném

Các kiểu khác cũng có TryParse

long.TryParse, double.TryParse, decimal.TryParse
DateTime.TryParse, Guid.TryParse, Enum.TryParse
bool.TryParse, byte.TryParse, ...

C# 7+ Pattern Matching

// Gọn nhẹ
if (int.TryParse(input, out int value))
    Console.WriteLine($"Parsed: {value}");
else
    Console.WriteLine("Invalid");