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

Parse chuỗi sang nullable int (int?) trong C#

int? là viết tắt của Nullable<int>, cho phép gán null cho kiểu giá trị.

Cách 1: Extension Method (Khuyến nghị, tái sử dụng)

public static class StringExtensions
{
    public static int? ToNullableInt(this string s)
    {
        if (string.IsNullOrWhiteSpace(s)) return null;
        return int.TryParse(s, out int result) ? result : null;
    }
}

// Sử dụng
string input1 = "123";
string input2 = "abc";
string input3 = null;

Console.WriteLine(input1.ToNullableInt()); // 123
Console.WriteLine(input2.ToNullableInt()); // (null - không in gì)
Console.WriteLine(input3.ToNullableInt()); // (null)

Cách 2: Ternary operator inline

string s = "456";
int? value = int.TryParse(s, out int i) ? i : (int?)null;

Cách 3: Dùng Convert (ném exception nếu fail)


// Chỉ dùng khi CHẮC CHẮN valid hoặc đã validate trước
string s = "789";
int? value = string.IsNullOrEmpty(s) ? null : Convert.ToInt32(s);

Cách 4: Pattern Matching (C# 7+)


int? ParseNullableInt(string s)
{
    return int.TryParse(s, out int i) ? i : null;
}

// Hoặc switch expression (C# 8)
int? ParseNullableInt2(string s) => s switch
{
    null => null,
    _ when int.TryParse(s, out int i) => i,
    _ => null
};

Nullable Reference Types (C# 8+) - Context


#nullable enable
string? input = GetInput();
int? parsed = input?.ToNullableInt(); // input có thể null
#nullable restore

Kiểm tra HasValue / GetValueOrDefault


int? nullable = "123".ToNullableInt();

if (nullable.HasValue)
    Console.WriteLine($"Value: {nullable.Value}"); // 123

// Hoặc
Console.WriteLine($"Value or default: {nullable.GetValueOrDefault()}"); // 123
Console.WriteLine($"Value or -1: {nullable.GetValueOrDefault(-1)}");    // 123

nullable = null;
Console.WriteLine($"Null case: {nullable.GetValueOrDefault(-1)}");      // -1

Lưu ý

  • int.TryParse an toàn, không ném exception.
  • int.Parse / Convert.ToInt32 ném FormatException / ArgumentNullException.
  • Extension method cho phép gọi "123".ToNullableInt() rất tự nhiên.
  • Có thể mở rộng cho long?, double?, decimal?, Guid?, DateTime? tương tự.