IRONSOFTWAREHOME

How to Handle Null Checking for Barcode Operations in C#

Curtis Chau
Curtis Chau
Updated: July 21, 2026

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 invalid 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:

  1. 1Install IronBarcode with NuGet Package Manager

    PM > Install-Package BarCode

  2. 2Copy 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);
    C#
  3. 3Deploy 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?

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).

Code128 barcode encoding SHP-20240001 used as the shipping label input

shipping-label.png (success path)

Blank white image with no barcode used to trigger the empty result path

blank-image.png (failure path, no barcode present)

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}");
}

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:

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}");

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:

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");

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.

EAN-8 barcode generated from the valid 7-digit input 1234567

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.

Code128 barcode encoding WH-SCAN-4471 used as the warehouse scan input for the validator example
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
}

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

View licensing options when the pipeline is ready for production.

Frequently Asked Questions

What is BarcodeResults in IronBarcode and how does it affect null checking?

BarcodeResults is a collection that IronBarcode's BarcodeReader.Read method returns. It will be null if the input image is invalid and empty if no barcodes are detected, which requires proper null-checking to avoid runtime exceptions.

How can guard clauses prevent exceptions in IronBarcode operations?

Guard clauses are applied in both read and write operations to check for null or invalid inputs before proceeding, preventing exceptions like NullReferenceException and ArgumentException in production.

What happens if you pass a null or empty string to BarcodeWriter.CreateBarcode?

Passing a null or empty string to BarcodeWriter.CreateBarcode throws an exception immediately. Input validation before the call ensures these exceptions are avoided, maintaining a stable encoding process.

How does ConfidenceThreshold affect the BarcodeReader in IronBarcode?

ConfidenceThreshold is a property in BarcodeReaderOptions that filters out low-quality reads during scanning. Reads below this threshold are discarded, so they don’t reach the results collection, improving the scan quality.

Can IronBarcode handle multiple barcode types in a single scan?

Yes, IronBarcode can handle multiple types in a single scan. Using the BarcodeReaderOptions with settings like ExpectBarcodeTypes can focus reads on specific symbologies, effectively managing mixed-content images.

Why is it important to validate BarcodeResults before downstream processing?

Validating BarcodeResults to ensure result count, value integrity, and type consistency prevents incorrect data from affecting database writes, API calls, and other system interactions.

What is the impact of not checking for null results in IronBarcode operations?

Not checking for null results can lead to NullReferenceExceptions during scanning operations, as accessing properties of a nonexistent BarcodeResult will fail.

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
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,422,100Version:2026.9just released

Get your free 30-day Trial Key instantly.
No credit card or account creation required
C# NuGet Library for PDF
Install with NuGet

Version: 2026.9

PM > Install-Package BarCode
nuget.org/packages/BarCode/
  1. In Solution Explorer, right-click References, Manage NuGet Packages
  2. Select Browse and search "IronBarCode"
  3. Select the package and install
C# PDF DLL
Download DLL

Version: 2026.9

  1. Download and unzip IronBarCode to a location such as ~/Libs within your Solution directory
  2. In Visual Studio Solution Explorer, right click References. Select Browse, "IronBarCode.dll"

Licenses from $999

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required