バーコード操作におけるNullチェックをC#で処理する方法
IronBarcode は、C# から BarcodeReader.Read まで、スキャン結果を BarcodeResults コレクションとして返します。 このメソッドは、入力画像が認識されない場合は null を返し、バーコードが検出されない場合は空のコレクションを返します。 BarcodeWriter.CreateBarcode 入力が null、空、または無効な形式の場合、例外がスローされます。
カメラ映像、文書アップロード、倉庫のスキャナーなど、実際のスキャン元では、必ずしも読み取り可能なバーコードが得られるとは限りません。 結果プロパティにアクセスしたり、null 値や空値をチェックせずにコレクションを反復処理したりすると、実行時に NullReferenceException が発生する可能性があります。書き込み API に無効化文字列を渡すと、ArgumentException が発生する可能性があります。 読み取り操作と書き込み操作の両方でガード句を使用することで、本番環境でこれらの例外が発生するのを防ぐことができます。
このハウツーでは、ガード句、信頼度フィルタリング、および再利用可能なバリデーターパターンを使用して、 IronBarcodeの読み取りおよび書き込み操作でnullおよび空の結果を処理する方法について説明します。
クイックスタート: バーコード操作でNull結果を処理する
IronBarcodeのガードパターンを使用して、結果プロパティにアクセスする前にBarcodeResultsコレクションを安全にチェックします。 まずは、この簡単な読み取りとチェック処理から始めます。
-
IronBarcode をNuGetパッケージマネージャでインストール
PM > Install-Package BarCode -
このコード スニペットをコピーして実行します。
using IronBarCode; 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); -
実際の環境でテストするためにデプロイする
今日プロジェクトで IronBarcode を使い始めましょう無料トライアル
IronBarcodeを使用したバーコード操作におけるヌルチェックの処理方法
- NuGetからIronBarcodeライブラリをダウンロード
BarcodeReader.Readを呼び出し、BarcodeResults戻り値を取得します。- 結果にアクセスする前にnullかどうかを確認してください。
- 下流で使用する前に、個々の
BarcodeResultプロパティを検証してください。 BarcodeReaderOptionsのConfidenceThresholdを設定して、スキャンレベルで低品質の読み取りをフィルタリングします。
Nullおよび空のバーコード結果をどのように処理しますか?
失敗モードは 2 つあります。入力が有効な画像でない場合は BarcodeResults が null になり、画像にバーコードが含まれていない場合は空になります。 Value にアクセスしたり、両方の条件を確認せずに反復処理したりすると、実行時例外が発生します。
処理ループに入る前に、両方の条件を確認してください。
入力
Code128バーコード付き配送ラベル(成功例)と、バーコードのない空白画像(失敗例)。
shipping-label.png(成功パス)
blank-image.png(エラー発生時の経路、バーコードなし)
:path=/static-assets/barcode/content-code-examples/how-to/null-checking/null-guard.cs
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}");
}
Imports IronBarCode
' BarcodeReader.Read() returns a BarcodeResults collection, not a single result
Dim results As BarcodeResults = 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 Nothing OrElse results.Count = 0 Then
' Log, return a default, or throw a domain-specific exception
Console.WriteLine("No barcodes found in the input image.")
Return
End If
' Collection is safe to iterate; each BarcodeResult holds one decoded barcode
For Each result As BarcodeResult 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) Then
Console.WriteLine($"Empty value detected for {result.BarcodeType}")
Continue For
End If
' BarcodeType identifies the symbology (Code128, QRCode, EAN8, etc.)
Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}")
Next
各 BarcodeResult は、Value および Text の文字列プロパティを提供し、どちらもデコードされたバーコードの内容を返します。 ひどく損傷したバーコードや部分的なスキャンでは、空白の値や空白文字が表示される場合があります。 空の値が下流システムに渡らないように、各結果に string.IsNullOrWhiteSpace を使用してください。
BarcodeReaderOptions には、結果コレクションに到達する前に低品質のリードを破棄するプロパティ (0.0 ~ 1.0) もあります。
:path=/static-assets/barcode/content-code-examples/how-to/null-checking/confidence-filter.cs
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}");
Imports 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.
Dim options As New BarcodeReaderOptions With {
.ConfidenceThreshold = 0.7 ' range 0.0 to 1.0; lower values accept weaker signals
}
Dim results As BarcodeResults = 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 Nothing OrElse results.Count = 0 Then
Console.WriteLine("No barcodes met the confidence threshold.")
Return
End If
For Each result In results
Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}")
Next
バーコード書き込みにNullセーフパターンを適用する方法
BarcodeWriter.CreateBarcode は文字列値と BarcodeWriterEncoding または BarcodeEncoding 列挙型を受け取ります。 null または空の文字列を渡すと、即座に例外が発生します。 フォーマットにも制約があります。EAN-8は7~8桁の数字を受け付け、UPC-Aは11~12桁の数字を受け付け、Code 128には文字数の制限があります。 呼び出し前に入力を検証することで、エンコード段階でこれらの例外が発生するのを防ぐことができます。
:path=/static-assets/barcode/content-code-examples/how-to/null-checking/null-safe-write.cs
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");
Imports IronBarCode
' Input may arrive from user input, a database, or an API response
Dim inputValue As String = GetValueFromUserOrDatabase() ' Could be Nothing
' Guard: null, empty, or whitespace input cannot produce a valid barcode
If String.IsNullOrWhiteSpace(inputValue) Then
Console.WriteLine("Cannot generate barcode: input value is null or empty.")
Return
End If
' Guard: format-specific constraints must be satisfied before encoding
' EAN-8 accepts exactly 7 or 8 numeric digits (the 8th is the check digit)
Dim encoding As BarcodeWriterEncoding = BarcodeWriterEncoding.EAN8
If encoding = BarcodeWriterEncoding.EAN8 AndAlso Not System.Text.RegularExpressions.Regex.IsMatch(inputValue, "^\d{7,8}$") Then
Console.WriteLine("EAN-8 requires exactly 7 or 8 numeric digits.")
Return
End If
' Input is validated; CreateBarcode will not throw for null or format mismatch
Dim barcode As GeneratedBarcode = BarcodeWriter.CreateBarcode(inputValue, encoding)
barcode.SaveAsPng("output-barcode.png")
出力
有効な7桁の入力(1234567)により、スキャン可能なEAN-8バーコードが生成されます。 ヌル値、空値、または非数値の入力はガード句によって捕捉され、エンコードステップには到達しません。
書き込みAPIも独自の内部検証を行います。チェックサムをチェックし、長さの制約を確認し、選択されたエンコーディングに対して無効な文字を拒否します。 上記のガード句は問題を早期に検知し、呼び出し元がエラーメッセージと回復パスを制御できるようにします。 サポートされているエンコーディングとその制約の完全なリストについては、バーコード作成方法とデータからバーコードを作成するガイドを参照してください。
下流処理前に結果を検証する方法
バーコードデータが別のシステム(データベースへの書き込み、API呼び出し、ラベルプリンターなど)に渡される場合、結果を渡す前に、結果の件数、値の整合性、および型のチェックを単一の再利用可能なメソッドに統合すると効果的です。
入力
バリデーターの読み取り対象として使用される、Code128バーコードの倉庫スキャン。
:path=/static-assets/barcode/content-code-examples/how-to/null-checking/barcode-validator.cs
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
}
Imports IronBarCode
Imports System.Collections.Generic
Imports 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 Module BarcodeValidator
Public Function GetValidResults(
imagePath As String,
Optional expectedType As BarcodeEncoding? = Nothing,
Optional confidenceThreshold As Double = 0.7) As List(Of BarcodeResult)
' Apply confidence threshold at scan level via BarcodeReaderOptions
Dim options As New BarcodeReaderOptions With {
.ConfidenceThreshold = confidenceThreshold
}
Dim results As BarcodeResults = BarcodeReader.Read(imagePath, options)
' Return empty list instead of null so callers never need to null-check the return value
If results Is Nothing OrElse results.Count = 0 Then
Return New List(Of BarcodeResult)()
End If
Return results _
.Where(Function(r) Not String.IsNullOrWhiteSpace(r.Value)) _ ' skip results with empty decoded data
.Where(Function(r) expectedType Is Nothing OrElse r.BarcodeType = expectedType) _ ' null accepts any symbology
.ToList()
End Function
End Module
' Usage: pass the image path and the symbology you expect
Dim validated = BarcodeValidator.GetValidResults(
"warehouse-scan.png",
expectedType:=BarcodeEncoding.Code128,
confidenceThreshold:=0.7)
If validated.Count = 0 Then
' No valid results; log the failure and skip downstream processing
Return
End If
' All results have passed null, empty, type, and confidence checks
For Each barcode In validated
SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString()) ' placeholder for your downstream call
Next barcode
このメソッドはnullではなく空のリストを返すため、呼び出し側は戻り値のnullチェックを行う必要がありません。 オプションの expectedType パラメータはシンボル体系でフィルタリングを行い、スキャンによって同じ画像から QR コードと Code 128 の両方が検出された場合に、下流システムが予期しない形式を受信するのを防ぎます。
複数のファイルに対して一括読み込みを行う場合は、ファイルごとに同じパターンを適用し、結果を集計します。 BarcodeReaderOptions の ExpectBarcodeTypes オプションは、事前に想定されるシンボル体系にスキャンを絞り込むため、不要な結果がバリデーターに到達する可能性が低くなります。
さらなる読み物
-バーコード読み取りチュートリアル:スキャン設定と読み取りオプション。
-出力データ形式ガイド:すべての BarcodeResult プロパティとその型。
-データからバーコードを作成する:各シンボル体系のエンコード制約。
- BarcodeReaderOptions APIリファレンス:完全な設定ドキュメント。
- IronBarcodeの変更履歴:バージョン固有の修正と機能追加。
パイプラインが本番稼働準備完了になったら、ライセンスオプションを確認してください。
よくある質問
BarCode処理におけるヌルチェックとは何ですか?
BarCode処理におけるNullチェックとは、実行時エラーを防ぎ、BarCode処理を円滑に行うために、BarCodeの結果や入力がNullかどうかを確認することです。
C#でのBarCode処理において、nullチェックが重要な理由は何ですか?
C#でのBarCode処理において、例外を回避し、BarCodeデータが欠落または無効である場合にアプリケーションが適切に処理できるようにするためには、Nullチェックが不可欠です。
IronBarcodeは、nullチェックにおいてどのように役立ちますか?
IronBarcodeには、nullチェックを簡単に処理するための組み込みメソッドが用意されており、開発者は複雑な検証ロジックを手動で実装することなく、BarCodeデータを安全に管理できます。
IronBarcode における null チェックのベストプラクティスにはどのようなものがありますか?
ベストプラクティスとしては、BarCodeResultsのnull値チェック、処理前の入力検証、信頼性の高いバーコードスキャン結果を確保するための信頼度フィルターの使用などが挙げられます。
IronBarcodeは、NULL出力となるのを防ぐために、信頼度に基づいて結果をフィルタリングできますか?
はい、IronBarcodeでは信頼度レベルに基づいてBARCODE検索結果をフィルタリングすることが可能です。これにより、無効な出力を減らし、BARCODE読み取りの高い精度を確保できます。
IronBarcodeを使用して入力データを検証する方法はありますか?
IronBarcode を使用すると、入力データの検証が可能になり、BarCode にエンコードされるデータが正確かつ完全であることを確認できるため、BarCode 生成時の問題を未然に防ぐことができます。
BarCodeの結果がnullの場合、適切に処理されないとどうなるでしょうか?
BARCODEの結果が null である場合の処理が行われないと、実行時例外が発生し、アプリケーションの処理フローが中断される可能性があります。その結果、クラッシュや誤動作を引き起こす恐れがあります。

