Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธี Parse String เป็น Nullable Int (int?) ใน C#

Nullable Value Types (int?, DateTime?, bool? เป็นต้น) อนุญาตให้ Value Type เก็บค่า null ได้ ใช้ Nullable<T> หรือ Syntax Sugar T?

Extension Method สำหรับ Parse String → int?

public static class StringExtensions
{
    // Parse String เป็น int? คืน null หาก Parse ไม่ได้
    public static int? ToNullableInt(this string s)
    {
        if (string.IsNullOrWhiteSpace(s)) return null;
        
        return int.TryParse(s, out int result) ? result : null;
    }
    
    // Overload: รองรับ NumberStyles และ Culture
    public static int? ToNullableInt(this string s, NumberStyles style, IFormatProvider provider)
    {
        if (string.IsNullOrWhiteSpace(s)) return null;
        return int.TryParse(s, style, provider, out int result) ? result : null;
    }
}

การใช้งาน

static void Main()
{
    string valid = "123";
    string invalid = "abc";
    string empty = "";
    string nullStr = null;
    string withSpaces = "  456  ";
    
    Console.WriteLine($"'{valid}' -> {valid.ToNullableInt()}");        // 123
    Console.WriteLine($"'{invalid}' -> {invalid.ToNullableInt()}");    // (null)
    Console.WriteLine($"'{empty}' -> {empty.ToNullableInt()}");        // (null)
    Console.WriteLine($"'null' -> {nullStr.ToNullableInt()}");         // (null)
    Console.WriteLine($"'{withSpaces}' -> {withSpaces.ToNullableInt()}"); // 456
    
    // ใช้กับ Nullable Arithmetic
    int? a = "10".ToNullableInt();
    int? b = "5".ToNullableInt();
    int? c = "xyz".ToNullableInt();
    
    Console.WriteLine($"a + b = {a + b}");      // 15
    Console.WriteLine($"a + c = {a + c}");      // (null) - Null Propagation
    Console.WriteLine($"a * 2 = {a * 2}");      // 20
}

ผลลัพธ์

'123' -> 123
'abc' -> 
'' -> 
'null' -> 
'  456  ' -> 456
a + b = 15
a + c = 
a * 2 = 20

วิธีอื่นๆ (Built-in)

1. int.TryParse (Standard)

string s = "123";
if (int.TryParse(s, out int value))
{
    int? result = value;
}
else
{
    int? result = null;
}

2. Ternary Operator (Inline)

int? result = int.TryParse(s, out int v) ? v : (int?)null;

3. Convert.ToInt32 (โยน Exception หาก Fail - ไม่แนะนำสำหรับ Nullable)

// ❌ โยน FormatException/ArgumentNullException
int? result = string.IsNullOrEmpty(s) ? null : Convert.ToInt32(s);

Nullable Types - Key Properties

int? x = 10;
int? y = null;

Console.WriteLine(x.HasValue);  // true
Console.WriteLine(x.Value);     // 10
Console.WriteLine(y.HasValue);  // false
// Console.WriteLine(y.Value);   // ❌ InvalidOperationException!

// Safe Access
Console.WriteLine(x.GetValueOrDefault());    // 10
Console.WriteLine(y.GetValueOrDefault());    // 0 (default(int))
Console.WriteLine(y.GetValueOrDefault(-1));  // -1 (custom default)

// Operators
Console.WriteLine(x == 10);   // true (Lifted Operator)
Console.WriteLine(y == null); // true
Console.WriteLine(x != y);    // true

Best Practice

  • ใช้ int.TryParse หรือ Extension Method ToNullableInt() สำหรับ Parsing
  • หลีกเลี่ยง .Value โดยตรง ใช้ .GetValueOrDefault() หรือ Pattern Matching
  • if (x is int value) Pattern Matching (C# 7+) Safe และชัดเจน
  • Enable #nullable enable (C# 8+) สำหรับ Static Analysis