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:

  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?

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)

: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}");
}
$vbLabelText   $csharpLabel

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

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");
$vbLabelText   $csharpLabel

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
: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
}
$vbLabelText   $csharpLabel

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 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,124,798 | 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.