How to Handle Null Checking for Barcode Operations in C#

BarcodeReader.Read() returns a BarcodeResults collection — not a single value. That collection can be null if the input image is unrecognized, or empty if no barcodes are detected. On the write side, BarcodeWriter.CreateBarcode() throws when passed null or invalid input. Both paths need guard clauses before the code touches result properties or generates output.

This guide covers null and empty result handling for IronBarcode read and write operations — the defensive patterns that prevent NullReferenceException and ArgumentException from reaching production.

Quickstart: Handle Null Results in Barcode Operations

Guard the BarcodeResults collection for both null and empty states before accessing any result properties to prevent runtime exceptions.

  1. Install IronBarcode with NuGet Package Manager

    PM > Install-Package BarCode
  2. 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);
  3. Deploy to test on your live environment

    Start using IronBarcode in your project today with a free trial

    arrow pointer

How to Handle Null and Empty Barcode Results?

BarcodeReader.Read() returns BarcodeResults, which is a collection of BarcodeResult objects. There are two failure modes to guard against: the collection itself being null (the input was not recognized as a valid image), and the collection being empty (valid image, but no barcodes found). Accessing .First(), .Value, or iterating without checking both conditions results in a runtime exception.

The standard guard pattern checks both conditions before entering the processing loop:

using IronBarCode;

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

// Null check: image may not be recognized
// Empty check: image recognized but no barcodes found
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;
}

foreach (BarcodeResult result in results)
{
    // Guard individual result properties
    if (string.IsNullOrWhiteSpace(result.Value))
    {
        Console.WriteLine($"Empty value detected for {result.BarcodeType}");
        continue;
    }

    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}");
}
using IronBarCode;

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

// Null check: image may not be recognized
// Empty check: image recognized but no barcodes found
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;
}

foreach (BarcodeResult result in results)
{
    // Guard individual result properties
    if (string.IsNullOrWhiteSpace(result.Value))
    {
        Console.WriteLine($"Empty value detected for {result.BarcodeType}");
        continue;
    }

    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}");
}
Imports IronBarCode

Dim results As BarcodeResults = BarcodeReader.Read("shipping-label.png")

' Null check: image may not be recognized
' Empty check: image recognized but no barcodes found
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

For Each result As BarcodeResult In results
    ' Guard individual result properties
    If String.IsNullOrWhiteSpace(result.Value) Then
        Console.WriteLine($"Empty value detected for {result.BarcodeType}")
        Continue For
    End If

    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}")
Next
$vbLabelText   $csharpLabel

Each BarcodeResult exposes .Value and .Text as string properties — both return the decoded barcode content. In normal operation these are populated, but edge cases exist: severely damaged barcodes, partial scans, or low-confidence detections can produce results where the value is empty or whitespace. Checking string.IsNullOrWhiteSpace() on individual results catches these cases before the data propagates.

The .Confidence property (a double between 0.0 and 1.0) provides an additional quality signal. For production systems, we can combine the null check with a confidence threshold:

double minimumConfidence = 0.7;

var validResults = results
    .Where(r => !string.IsNullOrWhiteSpace(r.Value) && r.Confidence >= minimumConfidence)
    .ToList();

if (validResults.Count == 0)
{
    Console.WriteLine("No barcodes met the confidence threshold.");
    return;
}
double minimumConfidence = 0.7;

var validResults = results
    .Where(r => !string.IsNullOrWhiteSpace(r.Value) && r.Confidence >= minimumConfidence)
    .ToList();

if (validResults.Count == 0)
{
    Console.WriteLine("No barcodes met the confidence threshold.");
    return;
}
Imports System
Imports System.Linq

Dim minimumConfidence As Double = 0.7

Dim validResults = results _
    .Where(Function(r) Not String.IsNullOrWhiteSpace(r.Value) AndAlso r.Confidence >= minimumConfidence) _
    .ToList()

If validResults.Count = 0 Then
    Console.WriteLine("No barcodes met the confidence threshold.")
    Return
End If
$vbLabelText   $csharpLabel

The BarcodeReaderOptions class also provides a MinimumConfidence property that filters at the scan level rather than post-processing. Setting this in the options object is cleaner for high-throughput batch scanning scenarios.

How to Apply Null-Safe Patterns to Barcode Writing?

BarcodeWriter.CreateBarcode() accepts a string value and a BarcodeWriterEncoding or BarcodeEncoding enum. Passing a null or empty string throws an exception. Additionally, format-specific constraints apply — EAN-8 requires exactly 7–8 numeric digits, UPC-A requires 11–12 digits, and Code 128 has a maximum character limit. Violating these constraints also throws.

The defensive pattern validates input before calling CreateBarcode():

using IronBarCode;

string inputValue = GetValueFromUserOrDatabase(); // Could be null

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

// Guard: format-specific constraints (example: EAN-8 requires 7-8 digits)
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;
}

GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(inputValue, encoding);
barcode.SaveAsPng("output-barcode.png");
using IronBarCode;

string inputValue = GetValueFromUserOrDatabase(); // Could be null

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

// Guard: format-specific constraints (example: EAN-8 requires 7-8 digits)
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;
}

GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(inputValue, encoding);
barcode.SaveAsPng("output-barcode.png");
Imports IronBarCode

Dim inputValue As String = GetValueFromUserOrDatabase() ' Could be null

' Guard: null, empty, or whitespace
If String.IsNullOrWhiteSpace(inputValue) Then
    Console.WriteLine("Cannot generate barcode: input value is null or empty.")
    Return
End If

' Guard: format-specific constraints (example: EAN-8 requires 7-8 digits)
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

Dim barcode As GeneratedBarcode = BarcodeWriter.CreateBarcode(inputValue, encoding)
barcode.SaveAsPng("output-barcode.png")
$vbLabelText   $csharpLabel

IronBarcode's writing API performs its own internal validation — it checks checksums, verifies length constraints, and rejects invalid characters for the selected encoding. These checks throw System.Exception with descriptive messages. The guard clauses above catch problems before they reach the library, which gives us control over error messaging and flow. 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 — we need a validation gate that checks result count, individual value integrity, and barcode type before the handoff. This consolidates the null-checking logic into a single reusable method.

using IronBarCode;
using System.Collections.Generic;
using System.Linq;

public static class BarcodeValidator
{
    public static List<BarcodeResult> GetValidResults(
        string imagePath,
        BarcodeEncoding? expectedType = null,
        double minimumConfidence = 0.7)
    {
        BarcodeResults results = BarcodeReader.Read(imagePath);

        if (results is null || results.Count == 0)
            return new List<BarcodeResult>();

        return results
            .Where(r => !string.IsNullOrWhiteSpace(r.Value))
            .Where(r => r.Confidence >= minimumConfidence)
            .Where(r => expectedType == null || r.BarcodeType == expectedType)
            .ToList();
    }
}

// Usage
var validated = BarcodeValidator.GetValidResults(
    "warehouse-scan.png",
    expectedType: BarcodeEncoding.Code128,
    minimumConfidence: 0.85);

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

// Safe to pass to downstream systems
foreach (var barcode in validated)
{
    SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString());
}
using IronBarCode;
using System.Collections.Generic;
using System.Linq;

public static class BarcodeValidator
{
    public static List<BarcodeResult> GetValidResults(
        string imagePath,
        BarcodeEncoding? expectedType = null,
        double minimumConfidence = 0.7)
    {
        BarcodeResults results = BarcodeReader.Read(imagePath);

        if (results is null || results.Count == 0)
            return new List<BarcodeResult>();

        return results
            .Where(r => !string.IsNullOrWhiteSpace(r.Value))
            .Where(r => r.Confidence >= minimumConfidence)
            .Where(r => expectedType == null || r.BarcodeType == expectedType)
            .ToList();
    }
}

// Usage
var validated = BarcodeValidator.GetValidResults(
    "warehouse-scan.png",
    expectedType: BarcodeEncoding.Code128,
    minimumConfidence: 0.85);

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

// Safe to pass to downstream systems
foreach (var barcode in validated)
{
    SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString());
}
Imports IronBarCode
Imports System.Collections.Generic
Imports System.Linq

Public Module BarcodeValidator
    Public Function GetValidResults(
        imagePath As String,
        Optional expectedType As BarcodeEncoding? = Nothing,
        Optional minimumConfidence As Double = 0.7) As List(Of BarcodeResult)

        Dim results As BarcodeResults = BarcodeReader.Read(imagePath)

        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)) _
            .Where(Function(r) r.Confidence >= minimumConfidence) _
            .Where(Function(r) expectedType Is Nothing OrElse r.BarcodeType = expectedType) _
            .ToList()
    End Function
End Module

' Usage
Dim validated = BarcodeValidator.GetValidResults(
    "warehouse-scan.png",
    expectedType:=BarcodeEncoding.Code128,
    minimumConfidence:=0.85)

If validated.Count = 0 Then
    ' No valid results — log and skip downstream processing
    Return
End If

' Safe to pass to downstream systems
For Each barcode In validated
    SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString())
Next
$vbLabelText   $csharpLabel

The validator method returns an empty list rather than null — this eliminates the need for callers to null-check the return value, which is a standard defensive pattern. The optional expectedType parameter ensures the downstream system only receives the barcode format it expects, which prevents mismatches 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 results. The BarcodeReaderOptions class supports ExpectBarcodeTypes to filter at the scan level, which reduces noise before validation.

Next Steps

Null checking for IronBarcode operations comes down to two patterns: guard the BarcodeResults collection (null + empty) before reading properties, and validate input strings before writing. The reusable validator above centralizes both concerns.

For deeper coverage, explore the reading barcodes tutorial for scan configuration, the output data formats guide for all BarcodeResult properties, and the API reference for the complete type surface.

Start a free 30-day trial to test these patterns against real scan data. When ready, view licensing options starting at $499.

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.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...

Read More
Ready to Get Started?
Nuget Downloads 2,094,439 | Version: 2026.3 just released
Still Scrolling Icon

Still Scrolling?

Want proof fast? PM > Install-Package BarCode
run a sample watch your string become a barcode.