# 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 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.
<hr />
*as-heading:2(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:
```cs
:title=Guard BarcodeResults for Null and Empty
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);
```
<div class="hsg-featured-snippet">
<h2>How to Handle Null Checking for Barcode Operations with IronBarcode</h2>
<ol>
<li><a class="js-modal-open" data-modal-id="trial-license-after-download" href="https://nuget.org/packages/BarCode/">Download the IronBarcode library from NuGet</a></li>
<li>Call <code>BarcodeReader.Read</code> and capture the <code>BarcodeResults</code> return</li>
<li>Check for null before accessing any result</li>
<li>Validate individual <code>BarcodeResult</code> properties before downstream use</li>
<li>Set <code>ConfidenceThreshold</code> on <code>BarcodeReaderOptions</code> to filter low-quality reads at the scan level</li>
</ol>
</div>
## 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).
<div style="display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap;">
<div class="content-img-align-center" style="width: 45%;">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/null-checking/input-shipping-label.png"
alt="Code128 barcode encoding SHP-20240001 used as the shipping label input"
class="img-responsive add-shadow" />
<p style="color: #181818; font-style: italic; text-align: center;">shipping-label.png (success path)</p>
</div>
</div>
<div class="content-img-align-center" style="width: 45%;">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/null-checking/input-blank-image.png"
alt="Blank white image with no barcode used to trigger the empty result path"
class="img-responsive add-shadow" />
<p style="color: #181818; font-style: italic; text-align: center;">blank-image.png (failure path, no barcode present)</p>
</div>
</div>
</div>
```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}");
}
```
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:
```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}");
```
---
## 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:
```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");
```
### 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.
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/null-checking/output-null-safe-write-barcode.png" alt="EAN-8 barcode generated from the valid 7-digit input 1234567" class="img-responsive add-shadow" />
</div>
</div>
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](https://ironsoftware.com/csharp/barcode/examples/csharp-create-barcode/) and the [create barcode from data guide](https://ironsoftware.com/csharp/barcode/how-to/create-barcode-from-data/).
---
## 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.
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/null-checking/input-warehouse-scan.png" alt="Code128 barcode encoding WH-SCAN-4471 used as the warehouse scan input for the validator example" class="img-responsive add-shadow" />
</div>
</div>
```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
}
```
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](https://ironsoftware.com/csharp/barcode/tutorials/reading-barcodes/) 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](https://ironsoftware.com/csharp/barcode/tutorials/reading-barcodes/): scan configuration and reading options.
- [Output Data Formats Guide](https://ironsoftware.com/csharp/barcode/how-to/output-data-formats/): all `BarcodeResult` properties and their types.
- [Create Barcode from Data](https://ironsoftware.com/csharp/barcode/how-to/create-barcode-from-data/): encoding constraints for each symbology.
- [BarcodeReaderOptions API Reference](https://ironsoftware.com/csharp/barcode/object-reference/api/IronBarCode.BarcodeReaderOptions.html): complete configuration documentation.
- [IronBarcode Changelog](https://ironsoftware.com/csharp/barcode/product-updates/changelog/): version-specific fixes and feature additions.
[View licensing options](https://ironsoftware.com/csharp/barcode/licensing/) when the pipeline is ready for production.
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:
1Install IronBarcode with NuGet Package Manager
PM > Install-Package BarCode
Install-Package BarCode
2Copy and run this code snippet.
using IronBarCode;BarcodeResults results = BarcodeReader.Read("label.png");// Guard: null or emptyif (results is null || results.Count == 0){Console.WriteLine("No barcodes detected."); return;}Console.WriteLine(results.First().Value);
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#
3Deploy 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
Call BarcodeReader.Read and capture the BarcodeResults return
Check for null before accessing any result
Validate individual BarcodeResult properties before downstream use
Set ConfidenceThreshold on BarcodeReaderOptions to 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)
using IronBarCode;// BarcodeReader.Read() returns a BarcodeResults collection, not a single resultBarcodeResults 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 barcodesif (results is null || results.Count == 0){ // Log, return a default, or throw a domain-specific exceptionConsole.WriteLine("No barcodes found in the input image."); return;}// Collection is safe to iterate; each BarcodeResult holds one decoded barcodeforeach (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}");}
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}");
}
ImportsIronBarCode' BarcodeReader.Read() returns a BarcodeResults collection, not a single resultDim results AsBarcodeResults = 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 barcodesIf results Is NothingOrElse results.Count = 0 Then ' Log, return a default, or throw a domain-specific exceptionConsole.WriteLine("No barcodes found in the input image.") ReturnEnd If' Collection is safe to iterate; each BarcodeResult holds one decoded barcodeFor Each result AsBarcodeResultIn results ' Guard individual result properties; partial scans or severely ' damaged barcodes can produce results where .Value is empty or whitespace IfString.IsNullOrWhiteSpace(result.Value) ThenConsole.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
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:
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 nullif (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}");
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}");
ImportsIronBarCode' 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 BarcodeReaderOptionsWith { .ConfidenceThreshold = 0.7 ' range 0.0 to 1.0; lower values accept weaker signals}Dim results AsBarcodeResults = 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 nullIf results Is NothingOrElse results.Count = 0 ThenConsole.WriteLine("No barcodes met the confidence threshold.") ReturnEnd IfFor Each result In resultsConsole.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}")Next
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:
using IronBarCode;// Input may arrive from user input, a database, or an API responsestring inputValue = GetValueFromUserOrDatabase(); // Could be null// Guard: null, empty, or whitespace input cannot produce a valid barcodeif (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 mismatchGeneratedBarcode barcode = BarcodeWriter.CreateBarcode(inputValue, encoding);barcode.SaveAsPng("output-barcode.png");
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");
ImportsIronBarCode' Input may arrive from user input, a database, or an API responseDim inputValue AsString = GetValueFromUserOrDatabase() ' Could be Nothing' Guard: null, empty, or whitespace input cannot produce a valid barcodeIfString.IsNullOrWhiteSpace(inputValue) ThenConsole.WriteLine("Cannot generate barcode: input value is null or empty.") ReturnEnd 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 AsBarcodeWriterEncoding = BarcodeWriterEncoding.EAN8If encoding = BarcodeWriterEncoding.EAN8AndAlsoNotSystem.Text.RegularExpressions.Regex.IsMatch(inputValue, "^\d{7,8}$") ThenConsole.WriteLine("EAN-8 requires exactly 7 or 8 numeric digits.") ReturnEnd If' Input is validated; CreateBarcode will not throw for null or format mismatchDim barcode AsGeneratedBarcode = 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.
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 expectvar 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 checksforeach (var barcode in validated){SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString()); // placeholder for your downstream call}
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
}
ImportsIronBarCodeImportsSystem.Collections.GenericImportsSystem.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.PublicModuleBarcodeValidator Public Function GetValidResults( imagePath AsString,Optional expectedType AsBarcodeEncoding? = Nothing,Optional confidenceThreshold AsDouble = 0.7) AsList(OfBarcodeResult) ' Apply confidence threshold at scan level via BarcodeReaderOptions Dim options As New BarcodeReaderOptionsWith { .ConfidenceThreshold = confidenceThreshold } Dim results AsBarcodeResults = BarcodeReader.Read(imagePath, options) ' Return empty list instead of null so callers never need to null-check the return value If results Is NothingOrElse results.Count = 0 Then Return New List(OfBarcodeResult)() End If Return results _ .Where(Function(r) NotString.IsNullOrWhiteSpace(r.Value)) _ ' skip results with empty decoded data .Where(Function(r) expectedType Is NothingOrElse r.BarcodeType = expectedType) _ ' null accepts any symbology .ToList() End FunctionEndModule' Usage: pass the image path and the symbology you expectDim 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 ReturnEnd If' All results have passed null, empty, type, and confidence checksFor Each barcode In validatedSendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString()) ' placeholder for your downstream callNext barcode
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.
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 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.