動くコード図鑑技術記事現場の渡り方キャリア論すべての記事About
C#

定石4: NULL値ハンドリングの違い

出典: C# DataReader vs DataAdapter — メモリ消費と性能の使い分け(業務SE 判断軸)定石4: NULL値ハンドリングの違い

定石4: NULL値ハンドリングの違い (csharp)#e782c17c1e04
// ✅定石4-b: DataReader用NULL安全ヘルパー
public static class ReaderEx
{
    public static int? GetIntOrNull(this SqlDataReader r, int i)
        => r.IsDBNull(i)? (int?)null : r.GetInt32(i);
 
    public static string GetStringOrNull(this SqlDataReader r, int i)
        => r.IsDBNull(i)? null : r.GetString(i);
 
    public static decimal GetDecimalOrZero(this SqlDataReader r, int i)
        => r.IsDBNull(i)? 0m : r.GetDecimal(i);
}
 
//使う側
while (reader.Read())
{
    int? id = reader.GetIntOrNull(0);
    string name = reader.GetStringOrNull(1);
    decimal amount = reader.GetDecimalOrZero(2);
}
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
  • id: #e782c17c1e04
  • lines: 20
  • extracted: 2026-06-10

Source収録記事

この snippet は記事の「定石4: NULL値ハンドリングの違い」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。

同じ記事から

4
図鑑トップ