バーコード操作におけるNullチェックをC#で処理する方法

Curtis Chau
Curtis Chau
更新日: 2026年7月21日

IronBarcodeはBarcodeReader.Readを通じてC#で結果をBarcodeResultsコレクションとして返します。 このメソッドは、入力画像が認識されない場合は null を返し、バーコードが検出されない場合は空のコレクションを返します。 BarcodeWriter.CreateBarcodeは、入力がnull、空、または無効な形式の場合に例外をスローします。

カメラ映像、文書アップロード、倉庫のスキャナーなど、実際のスキャン元では、必ずしも読み取り可能なバーコードが得られるとは限りません。 結果のプロパティへのアクセスや、コレクションをnullまたは空の値を確認せずに反復することは、実行時にNullReferenceExceptionを引き起こす可能性があります。無効な文字列をWrite APIに渡すと、ArgumentExceptionを引き起こす可能性があります。 読み取り操作と書き込み操作の両方でガード句を使用することで、本番環境でこれらの例外が発生するのを防ぐことができます。

このハウツーでは、IronBarcodeの読み取りおよび書き込み操作でguard句、信頼度フィルタリング、再利用可能なバリデータパターンを使用してnullおよび空の結果を処理する方法を説明します。


クイックスタート: バーコード操作でNull結果を処理する

IronBarcodeのガードパターンを使用して、結果のプロパティにアクセスする前にBarcodeResultsコレクションを安全に確認してください。 まずは、この簡単な読み物とチェック項目から始めてみましょう。

  1. 1IronBarcode を NuGet Package Manager でインストールします

    PM > Install-Package BarCode

  2. 2このコード スニペットをコピーして実行します。

    using IronBarCode;
    using System;
    using System.Linq;
    
    BarcodeResults results = BarcodeReader.Read("label.png");
    
    // Guard: null or empty
    if (results is null || results.Count == 0)
    {
        Console.WriteLine("No barcodes detected.");
        return;
    }
    
    Console.WriteLine(results.First().Value);
  3. 3実際の環境でテストするためにデプロイする

    今日からご自身のプロジェクトでIronBarcodeを使い始めるには、無料トライアルをお試しください。
    arrow pointer

Nullおよび空のバーコード結果をどのように処理しますか?

失敗モードは2つあります: 入力が有効な画像でない場合はBarcodeResultsがnullになり、画像にバーコードが含まれていない場合は空になります。 First、Valueにアクセスしたり、両方の条件を確認せずに繰り返したりすると、ランタイム例外が発生します。

処理ループに入る前に、両方の条件を確認してください。

入力

Code128バーコードの配送ラベル(成功パス)とバーコードを含まない空の画像(失敗パス)。

出荷ラベルの入力として使用される、SHP-20240001 をエンコードした Code128 バーコード

shipping-label.png(成功パス)

空の結果パスをトリガーするために使用される、バーコードのない白紙の画像

blank-image.png(エラー発生時の経路、バーコードなし)

using IronBarCode;

// BarcodeReader.Read() returns a BarcodeResults collection, not a single result
BarcodeResults results = BarcodeReader.Read("shipping-label.png");

// Null check: image was not recognized as a valid image source
// Empty check: image was valid but contained no detectable barcodes
if (results is null || results.Count == 0)
{
    // Log, return a default, or throw a domain-specific exception
    Console.WriteLine("No barcodes found in the input image.");
    return;
}

// Collection is safe to iterate; each BarcodeResult holds one decoded barcode
foreach (BarcodeResult result in results)
{
    // Guard individual result properties; partial scans or severely
    // damaged barcodes can produce results where .Value is empty or whitespace
    if (string.IsNullOrWhiteSpace(result.Value))
    {
        Console.WriteLine($"Empty value detected for {result.BarcodeType}");
        continue;
    }

    // BarcodeType identifies the symbology (Code128, QRCode, EAN8, etc.)
    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}");
}

各BarcodeResultはValueおよびTextという文字列プロパティを提供し、どちらもデコードされたバーコード内容を返します。 ひどく損傷したバーコードや部分的なスキャンでは、空白の値や空白文字が表示される場合があります。 ダウンストリームシステムに空の値が到達しないように各結果にstring.IsNullOrWhiteSpaceを使用してください。

BarcodeReaderOptionsには低品質の読み取りを結果コレクションに到達する前に除外するConfidenceThresholdプロパティがあります(0.0から1.0まで):

using IronBarCode;

// ConfidenceThreshold filters low-quality reads before they enter the
// BarcodeResults collection. Reads below the threshold are discarded
// during scanning, not after, so no post-filtering of the collection is needed.
var options = new BarcodeReaderOptions
{
    ConfidenceThreshold = 0.7  // range 0.0 to 1.0; lower values accept weaker signals
};

BarcodeResults results = BarcodeReader.Read("shipping-label.png", options);

// Still check for null and empty even with a threshold applied;
// an image with no barcodes returns an empty collection, not null
if (results is null || results.Count == 0)
{
    Console.WriteLine("No barcodes met the confidence threshold.");
    return;
}

foreach (var result in results)
    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}");

バーコード書き込みにNullセーフパターンを適用する方法

BarcodeWriter.CreateBarcodeは文字列値とBarcodeWriterEncodingまたはBarcodeEncoding列挙型を受け取ります。 null または空の文字列を渡すと、即座に例外が発生します。 フォーマットの制約も適用されます:EAN-8は7から8の数字を受け取り、UPC-Aは11から12、Code 128は文字数制限があります。 呼び出し前に入力を検証することで、エンコード段階でこれらの例外が発生するのを防ぐことができます。

using IronBarCode;

// Input may arrive from user input, a database, or an API response
string inputValue = GetValueFromUserOrDatabase(); // Could be null

// Guard: null, empty, or whitespace input cannot produce a valid barcode
if (string.IsNullOrWhiteSpace(inputValue))
{
    Console.WriteLine("Cannot generate barcode: input value is null or empty.");
    return;
}

// Guard: format-specific constraints must be satisfied before encoding
// EAN-8 accepts exactly 7 or 8 numeric digits (the 8th is the check digit)
BarcodeWriterEncoding encoding = BarcodeWriterEncoding.EAN8;
if (encoding == BarcodeWriterEncoding.EAN8 && !System.Text.RegularExpressions.Regex.IsMatch(inputValue, @"^\d{7,8}$"))
{
    Console.WriteLine("EAN-8 requires exactly 7 or 8 numeric digits.");
    return;
}

// Input is validated; CreateBarcode will not throw for null or format mismatch
GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(inputValue, encoding);
barcode.SaveAsPng("output-barcode.png");

出力

有効な7桁の入力(1234567)はスキャン可能なEAN-8バーコードを生成します。 ヌル値、空値、または非数値の入力はガード句によって捕捉され、エンコードステップには到達しません。

有効な7桁の入力値1234567から生成されたEAN-8バーコード

書き込みAPIも独自の内部検証を行います。チェックサムをチェックし、長さの制約を確認し、選択されたエンコーディングに対して無効な文字を拒否します。 上記のガード句は問題を早期に検知し、呼び出し元がエラーメッセージと回復パスを制御できるようにします。 サポートされるエンコーディングとその制約の完全なリストについては、バーコード作成方法とデータからのバーコード作成ガイドを参照してください。


下流処理前に結果を検証する方法

バーコードデータが別のシステム(データベースへの書き込み、API呼び出し、ラベルプリンターなど)に渡される場合、結果を渡す前に、結果の件数、値の整合性、および型のチェックを単一の再利用可能なメソッドに統合すると効果的です。

入力

読み取りターゲットとして使用されるCode128バーコード倉庫スキャン。

検証例の倉庫スキャン入力として使用されるCode128バーコードエンコーディングWH-SCAN-4471
using IronBarCode;
using System.Collections.Generic;
using System.Linq;

// Reusable validation helper — consolidates null, empty, value, and
// expected-format checks into a single method. Returns an empty list
// (never null) so callers do not need to null-check the return value.
public static class BarcodeValidator
{
    public static List<BarcodeResult> GetValidResults(
        string imagePath,
        BarcodeEncoding? expectedType = null,
        double confidenceThreshold = 0.7)
    {
        // Apply confidence threshold at scan level via BarcodeReaderOptions
        var options = new BarcodeReaderOptions
        {
            ConfidenceThreshold = confidenceThreshold
        };

        BarcodeResults results = BarcodeReader.Read(imagePath, options);

        // Return empty list instead of null so callers never need to null-check the return value
        if (results is null || results.Count == 0)
            return new List<BarcodeResult>();

        return results
            .Where(r => !string.IsNullOrWhiteSpace(r.Value))           // skip results with empty decoded data
            .Where(r => expectedType == null || r.BarcodeType == expectedType) // null accepts any symbology
            .ToList();
    }
}

// Usage: pass the image path and the symbology you expect
var validated = BarcodeValidator.GetValidResults(
    "warehouse-scan.png",
    expectedType: BarcodeEncoding.Code128,
    confidenceThreshold: 0.7);

if (validated.Count == 0)
{
    // No valid results; log the failure and skip downstream processing
    return;
}

// All results have passed null, empty, type, and confidence checks
foreach (var barcode in validated)
{
    SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString()); // placeholder for your downstream call
}

このメソッドはnullではなく空のリストを返すため、呼び出し側は戻り値のnullチェックを行う必要がありません。 オプションのexpectedTypeパラメーターはシンボロジーでフィルターをかけ、スキャンが同じ画像からQRコードとCode 128を両方キャプチャする際に下流システムへの予期しないフォーマットの受信を防ぎます。

複数ファイルにわたるバッチ読み取りの場合、ファイルごとに同じパターンを適用し、結果を集計します。 BarcodeReaderOptionsのExpectBarcodeTypesオプションは、予想されるシンボロジーへスキャンを事前に絞り込み、検証者に届く不要な結果を減らします。


さらなる読み物

ライセンスオプションを表示してパイプラインを本番対応にしてください。

よくある質問

IronBarcodeにおけるBarcodeResultsとは何ですか、それはヌルチェックにどう影響しますか?

BarcodeResultsは、IronBarcodeのBarcodeReader.Readメソッドが返すコレクションです。入力画像が無効である場合はヌルになりますし、バーコードが検出されない場合は空になります。これには、ランタイム例外を避けるための適切なヌルチェックが必要です。

IronBarcodeの操作でガード句はどのようにして例外を防ぐことができますか?

ガード句は読み取りおよび書き込み操作の両方に適用され、ヌルまたは無効な入力をチェックしてから続行することで、本番環境でNullReferenceExceptionやArgumentExceptionのような例外を防ぎます。

BarcodeWriter.CreateBarcodeにヌルまたは空の文字列を渡した場合、何が起こりますか?

BarcodeWriter.CreateBarcodeにヌルまたは空の文字列を渡すと、即座に例外がスローされます。呼び出し前の入力検証により、これらの例外を回避し、安定したエンコードプロセスが保たれます。

ConfidenceThresholdはIronBarcodeのBarcodeReaderにどのように影響しますか?

ConfidenceThresholdはBarcodeReaderOptionsのプロパティであり、スキャン中に低品質な読み取りをフィルタリングします。このしきい値以下の読み取りは破棄され、結果コレクションに到達しないため、スキャンの質が向上します。

IronBarcodeは単一のスキャンで複数のバーコードタイプを処理できますか?

はい、IronBarcodeは単一のスキャンで複数のタイプを処理できます。BarcodeReaderOptionsを使用して、ExpectBarcodeTypesのような設定を使用すると、特定のシンボロジーに焦点を当てて読み取りを行うことができ、混在するコンテンツ画像を効果的に管理できます。

下流処理の前にBarcodeResultsをバリデートすることがなぜ重要なのですか?

BarcodeResultsをバリデートすることにより、結果の数、値の整合性、および型の一貫性を確認することで、不正確なデータがデータベースの書き込みやAPIコール、その他のシステムの相互作用に影響を与えるのを防ぎます。

IronBarcode操作でヌル結果をチェックしないとどのような影響がありますか?

ヌル結果をチェックしないと、スキャン操作中にNullReferenceExceptionが発生する可能性があります。存在しないBarcodeResultのプロパティにアクセスしようとすると失敗します。

IronBarcodeの再利用可能なバリデータパターンはどのように機能しますか?

IronBarcodeの再利用可能なバリデータパターンは、ヌルチェック、空チェック、値の整合性、期待されるフォーマットの検証を統合して1つのメソッドにまとめ、結果が下流で使用される前に検証プロセスを簡素化します。

BarcodeWriterEncodingがバーコード作成中に取り扱う制約にはどのようなものがありますか?

BarcodeWriterEncodingは、バーコードの種類に応じて文字列の長さや文字の有効性の制約を課します。例えば、EAN-8は7桁または8桁の数字でなければなりません。正しくフォーマットされた入力により、エンコード中の例外を回避します。

IronBarcodeはスキャンされたバーコードの品質をどのようにして確保しますか?

IronBarcodeは、BarcodeReaderOptionsのConfidenceThresholdなどのプロパティを使用して、高品質なバーコードのみが結果に含まれるようにします。この事前スキャンフィルタは、低品質な読み取りがさらなる処理に進む前に破棄されることを意味します。

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

もっと読む

準備はできましたか?

NuGetダウンロード数 2,575,633バージョン:2026.11ちょうどリリースされました