バーコード操作におけるNullチェックをC#で処理する方法
IronBarcodeは、BarcodeResultsコレクションとして返します。 このメソッドは、入力画像が認識されない場合は null を返し、バーコードが検出されない場合は空のコレクションを返します。 入力がnull、空、または無効な形式の場合、BarcodeWriter.CreateBarcodeが例外をスローします。
カメラ映像、文書アップロード、倉庫のスキャナーなど、実際のスキャン元では、必ずしも読み取り可能なバーコードが得られるとは限りません。 結果のプロパティーにアクセスするか、変数にイテレーションしてもnullまたは空の値を確認しないと、実行時にNullReferenceExceptionが発生する可能性があります。無効な文字列をwrite APIに渡すと、ArgumentExceptionが発生する可能性があります。 読み取り操作と書き込み操作の両方でガード句を使用することで、本番環境でこれらの例外が発生するのを防ぐことができます。
このハウツーでは、IronBarcodeの読み取りおよび書き込み操作でguard句、信頼度フィルタリング、再利用可能なバリデータパターンを使用してnullおよび空の結果を処理する方法を説明します。
クイックスタート: バーコード操作でNull結果を処理する
IronBarcodeのガードパターンを使用して、BarcodeResultsコレクションを安全にチェックし、結果のプロパティーにアクセスする前に確認してください。 まずは、この簡単な読み物とチェック項目から始めてみましょう。
-
1Install IronBarcode with NuGet Package Manager
-
2このコード スニペットをコピーして実行します。
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);C# -
3実際の環境でテストするためにデプロイする
今日プロジェクトで IronBarcode を使い始めましょう無料トライアル
IronBarcodeを使用したバーコード操作におけるヌルチェックの処理方法
- NuGetからIronBarcodeライブラリをダウンロード
BarcodeReader.Readを呼び出し、BarcodeResults戻り値を取得します。- 結果にアクセスする前にnullかどうかを確認してください。
- 下流で使用する前に、個々の
BarcodeResultプロパティを検証してください。 BarcodeReaderOptionsのConfidenceThresholdを設定して、スキャンレベルで低品質の読み取りをフィルタリングします。
Nullおよび空のバーコード結果をどのように処理しますか?
失敗モードは2つあります。入力が有効な画像でない場合、BarcodeResultsはnullになりますが、画像内にバーコードがない場合は空になります。 Valueにアクセスするか、両方の条件を確認せずに変数にイテレーションすると、実行時例外が発生します。
処理ループに入る前に、両方の条件を確認してください。
入力
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}");
}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各Text文字列プロパティーを提供し、どちらもデコードされたバーコードの内容を返します。 ひどく損傷したバーコードや部分的なスキャンでは、空白の値や空白文字が表示される場合があります。 下流システムに空の値が届かないようにするために、各結果に対してstring.IsNullOrWhiteSpaceを使用します。
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}");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セーフパターンを適用する方法
BarcodeEncoding列挙を受け取ります。 null または空の文字列を渡すと、即座に例外が発生します。 形式の制約も適用されます: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");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桁の入力(EAN-8バーコードを生成します。 ヌル値、空値、または非数値の入力はガード句によって捕捉され、エンコードステップには到達しません。

書き込みAPIも独自の内部検証を行います。チェックサムをチェックし、長さの制約を確認し、選択されたエンコーディングに対して無効な文字を拒否します。 上記のガード句は問題を早期に検知し、呼び出し元がエラーメッセージと回復パスを制御できるようにします。 サポートされているエンコーディングとその制約の完全なリストについては、バーコード作成方法とデータからバーコードを作成するガイドを参照してください。
下流処理前に結果を検証する方法
バーコードデータが別のシステム(データベースへの書き込み、API呼び出し、ラベルプリンターなど)に渡される場合、結果を渡す前に、結果の件数、値の整合性、および型のチェックを単一の再利用可能なメソッドに統合すると効果的です。
入力
検証対象として読み込むCode128バーコードの倉庫スキャン。

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チェックを行う必要がありません。 オプションのCode 128の両方を同じ画像から取得した場合、下流システムに予期しないフォーマットが届かないようにします。
複数のファイルに対して一括読み込みを行う場合は、ファイルごとに同じパターンを適用し、結果を集計します。 BarcodeReaderOptionsで予期されるシンボロジーに事前にスキャンを絞るため、バリデーターに到達する不必要な結果が少なくなります。
さらなる読み物
-バーコード読み取りチュートリアル:スキャン設定と読み取りオプション。
- 出力データフォーマットガイド: すべての
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 である場合の処理が行われないと、実行時例外が発生し、アプリケーションの処理フローが中断される可能性があります。その結果、クラッシュや誤動作を引き起こす恐れがあります。
How does IronBarcode's reusable validator pattern work?
IronBarcode's reusable validator pattern consolidates null checks, empty checks, value integrity, and expected format validation into a single method, simplifying the validation process before results are used downstream.
What are some constraints that BarcodeWriterEncoding handles during barcode creation?
BarcodeWriterEncoding imposes constraints like string length and character validity based on the barcode type. For example, EAN-8 must have 7 or 8 numeric digits. Correctly formatted input avoids exceptions during encoding.
How does IronBarcode ensure the quality of scanned barcodes?
IronBarcode uses properties such as ConfidenceThreshold in BarcodeReaderOptions to ensure only high-quality barcodes are included in results. This pre-scanning filter means low-quality reads are discarded before further processing.

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