How to Handle Null Checking for Barcode Operations in C#
IronBarcode returns scan results as a BarcodeResults collection in C# through BarcodeReader.Read. This method returns null if the input image is unrecognized, or an empty collection if no barcodes are detected. BarcodeWriter.CreateBarcode throws an exception if the input is null, empty, or in an invalid format.
Real-world scan sources such as camera feeds, document uploads, and warehouse scanners may not always provide a readable barcode. Accessing result properties or iterating the collection without checking for null or empty values can cause a NullReferenceException at runtime. Passing invalidate strings to the write API can result in an ArgumentException. Using guard clauses in both read and write operations helps prevent these exceptions in production.
This how to explains how to handle null and empty results in IronBarcode read and write operations by using guard clauses, confidence filtering, and a reusable validator pattern.
Quickstart: Handle Null Results in Barcode Operations
Use IronBarcode's guard pattern to safely check the BarcodeResults collection before accessing any result properties. Get started immediately with this minimal read and check:
-
Install IronBarcode with NuGet Package Manager
PM > Install-Package BarCode -
Copy and run this code snippet.
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); -
Deploy to test on your live environment
Start using IronBarcode in your project today with a free trial
How to Handle Null Checking for Barcode Operations with IronBarcode
- Download the IronBarcode library from NuGet
- Call
BarcodeReader.Readand capture theBarcodeResultsreturn - Check for null before accessing any result
- Validate individual
BarcodeResultproperties before downstream use - Set
ConfidenceThresholdonBarcodeReaderOptionsto filter low-quality reads at the scan level
How to Handle Null and Empty Barcode Results?
There are two failure modes: BarcodeResults is null if the input is not a valid image, and empty if the image contains no barcodes. Accessing First, Value, or iterating without verifying both conditions will cause a runtime exception.
Check both conditions before entering the processing loop:
Input
A Code128 barcode shipping label (success path) and a blank image containing no barcode (failure path).
shipping-label.png (success path)
blank-image.png (failure path, no barcode present)
: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
Each BarcodeResult provides Value and Text string properties, both returning the decoded barcode content. Severely damaged barcodes or partial scans may produce empty or whitespace values. Use string.IsNullOrWhiteSpace on each result to prevent empty values from reaching downstream systems.
BarcodeReaderOptions also has a ConfidenceThreshold property (0.0 to 1.0) that drops low-quality reads before they reach the results collection:
: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
How to Apply Null-Safe Patterns to Barcode Writing?
BarcodeWriter.CreateBarcode takes a string value and a BarcodeWriterEncoding or BarcodeEncoding enum. Passing a null or empty string throws immediately. Format constraints also apply: EAN-8 accepts 7 to 8 numeric digits, UPC-A accepts 11 to 12, and Code 128 has a character limit. Validating input before the call keeps these exceptions out of the encoding step:
: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")
Output
A valid 7-digit input (1234567) produces a scannable EAN-8 barcode. Null, empty, or non-numeric inputs are caught by the guard clauses and never reach the encoding step.
The writing API does its own internal validation too: it checks checksums, verifies length constraints, and rejects invalid characters for the selected encoding. The guard clauses above catch problems earlier, giving the caller control over the error message and the recovery path. For a complete list of supported encodings and their constraints, see the barcode creation how-to and the create barcode from data guide.
How to Validate Results Before Downstream Processing?
When barcode data feeds into another system (a database write, an API call, a label printer), it helps to consolidate the result count, value integrity, and type checks into a single reusable method before passing the data on:
Input
A Code128 barcode warehouse scan used as the read target for the validator.
: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
The method returns an empty list rather than null, so callers never need to null-check the return value. The optional expectedType parameter filters by symbology, which prevents the downstream system from receiving unexpected formats when a scan picks up both a QR code and a Code 128 from the same image.
For batch reading across multiple files, apply the same pattern per file and aggregate the results. The ExpectBarcodeTypes option on BarcodeReaderOptions narrows the scan to expected symbologies upfront, so fewer unwanted results reach the validator.
Further Reading
- Reading Barcodes Tutorial: scan configuration and reading options.
- Output Data Formats Guide: all
BarcodeResultproperties and their types. - Create Barcode from Data: encoding constraints for each symbology.
- BarcodeReaderOptions API Reference: complete configuration documentation.
- IronBarcode Changelog: version-specific fixes and feature additions.
View licensing options when the pipeline is ready for production.
Frequently Asked Questions
What is null checking in barcode operations?
Null checking in barcode operations involves verifying if a barcode result or input is null to prevent runtime errors and ensure smooth barcode processing.
Why is null checking important in C# barcode operations?
Null checking is crucial in C# barcode operations to avoid exceptions and ensure that the application can gracefully handle cases where barcode data might be missing or invalid.
How can IronBarcode assist with null checking?
IronBarcode provides built-in methods to easily handle null checks, allowing developers to safely manage barcode data without manually implementing complex validation logic.
What are some best practices for null checking in IronBarcode?
Best practices include checking BarcodeResults for null values, validating inputs before processing, and using confidence filters to ensure reliable barcode scanning results.
Can IronBarcode filter results by confidence to avoid null outputs?
Yes, IronBarcode allows filtering of barcode results by confidence levels, which helps in reducing null outputs and ensures high accuracy in barcode reading.
Is there a way to validate write inputs using IronBarcode?
IronBarcode enables validation of write inputs to ensure that the data being encoded into barcodes is correct and complete, preventing issues during barcode generation.
What happens if a null barcode result is not handled?
If a null barcode result is not handled, it can lead to runtime exceptions and disrupt the flow of the application, causing potential crashes or incorrect operations.

