C# String Equals (How it Works for Developers)
When working with PDF documents in C# applications, comparing strings is a surprisingly common task, whether you're checking extracted text, verifying metadata, or conditionally modifying documents. The string.Equals method in C# provides a precise way to compare string objects, and when combined with IronPDF, it becomes a powerful tool in your PDF automation toolkit.
In this article, we'll explore what string.Equals is, why it matters in .NET, and how you can use it effectively alongside IronPDF, the leading .NET PDF library for generation and manipulation.
What is string.Equals in C#?
The C string equals method, known in C# as string.Equals, is used to compare the contents of two parameters representing either strings or other compatible objects. You can pass either plain string values or a type object that will be converted to a string during the comparison. Unlike the == operator, which is syntactic sugar for equals string, using string.Equals explicitly allows you to:
Specify comparison rules (such as case sensitive comparison or culture insensitive comparison).
Avoid confusion with overloaded operators.
- Improve readability in conditional logic.
In the .NET Framework, the method signature often looks like:
public bool Equals(string value, StringComparison comparisonType)
public bool Equals(string value, StringComparison comparisonType)
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'public bool Equals(string value, StringComparison comparisonType)
Here, public bool indicates the return value will always be true or false depending on the comparison result.
Basic Syntax
string.Equals(str1, str2)
string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase)
string.Equals(str1, str2)
string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase)
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'string.Equals(str1, str2) string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase)
This method takes two parameters: the two strings or string objects to compare, and optionally the type of comparison to perform. The return value is a boolean. The method will return true if both arguments are equal according to the comparison rules, or return false otherwise.
You can compare two strings using different StringComparison options like:
Ordinal (binary comparison, case-sensitive comparison)
OrdinalIgnoreCase (case-insensitive comparison)
CurrentCulture
- InvariantCultureIgnoreCase
How It Works with IronPDF
IronPDF is a powerful .NET PDF library that allows you to search, extract, and manipulate text within PDF documents. By using string.Equals, you can:
Compare extracted string value to a known value.
Check metadata fields like title, author, and keywords.
- Conditionally edit your PDF documents, letting you add annotations, highlights, or watermarks based on string comparison results.
Let's walk through the following examples where string.Equals proves useful in IronPDF workflows.
Example 1: Compare Extracted Text with string.Equals
Imagine you're scanning a PDF invoice and want to validate whether it includes a specific company name. Here’s an example demonstrating how to avoid common pitfalls like null reference exception and how the method checks equality robustly.
The following example will be using this PDF:
using IronPdf;
using IronPdf.Editing;
class Program
{
public static void Main(string[] args)
{
var pdf = new IronPdf.PdfDocument("invoice.pdf");
string extractedText = pdf.ExtractAllText();
var lines = extractedText.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
if (string.Equals(line.Trim(), "Acme Corporation", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Exact match found: Acme Corporation");
}
}
}
}
using IronPdf;
using IronPdf.Editing;
class Program
{
public static void Main(string[] args)
{
var pdf = new IronPdf.PdfDocument("invoice.pdf");
string extractedText = pdf.ExtractAllText();
var lines = extractedText.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
if (string.Equals(line.Trim(), "Acme Corporation", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Exact match found: Acme Corporation");
}
}
}
}
Imports Microsoft.VisualBasic
Imports IronPdf
Imports IronPdf.Editing
Friend Class Program
Public Shared Sub Main(ByVal args() As String)
Dim pdf = New IronPdf.PdfDocument("invoice.pdf")
Dim extractedText As String = pdf.ExtractAllText()
Dim lines = extractedText.Split( { ControlChars.Cr, ControlChars.Lf }, StringSplitOptions.RemoveEmptyEntries)
For Each line In lines
If String.Equals(line.Trim(), "Acme Corporation", StringComparison.OrdinalIgnoreCase) Then
Console.WriteLine("Exact match found: Acme Corporation")
End If
Next line
End Sub
End Class
Note: The method returns a boolean value indicating whether the two string objects contain the same value.
Why This Matters:
As we see in the following output, using string.Equals with StringComparison.OrdinalIgnoreCase ensures that "ACME CORPORATION" and "Acme Corporation" are treated as equal — essential in OCR or text extraction scenarios where case sensitive differences could cause different behavior.
Output
Example 2: Validate PDF Metadata Using string.Equals
PDF files often contain metadata fields like Title, Author, and Subject. IronPDF is capable of being used to read these properties, making it easy to inspect and compare them.
using IronPdf;
var pdf = new IronPdf.PdfDocument("invoice.pdf");
string author = pdf.MetaData.Author;
if (string.Equals(author, "Iron Software", StringComparison.InvariantCulture))
{
Console.WriteLine("Invoice was issued by Iron Software.");
}
using IronPdf;
var pdf = new IronPdf.PdfDocument("invoice.pdf");
string author = pdf.MetaData.Author;
if (string.Equals(author, "Iron Software", StringComparison.InvariantCulture))
{
Console.WriteLine("Invoice was issued by Iron Software.");
}
Imports IronPdf
Private pdf = New IronPdf.PdfDocument("invoice.pdf")
Private author As String = pdf.MetaData.Author
If String.Equals(author, "Iron Software", StringComparison.InvariantCulture) Then
Console.WriteLine("Invoice was issued by Iron Software.")
End If
This method is particularly useful in systems where validation based on metadata prevents processing not a string or invalid files.
Output
Example 3: Add Watermark Based on Text Match
You may want to automatically watermark PDF documents that contain certain keywords. Here's how to do that:
using IronPdf;
using IronPdf.Editing;
License.LicenseKey = "IRONSUITE.WRITERS.21046-907F5E67CC-AHYQW6L-RCHLPMRJMU4G-SET72XAF2JNY-LQK45E5JPLGW-XOLPVBEBLHV7-2LHKZRWUZWMO-5LNIZSPF4BM6-UHUH4R-T4MMJ4MEIYSQEA-DEPLOYMENT.TRIAL-LDG2MK.TRIAL.EXPIRES.16.NOV.2025";
var pdf = new IronPdf.PdfDocument("invoice.pdf");
string content = pdf.ExtractAllText();
var lines = content.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
if (string.Equals(line.Trim(), "DRAFT", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("The document is a draft.");
// Corrected HTML and CSS
string watermark = @"<div style='color:red; font-size:72px; font-weight:bold;'>DRAFT</div>";
pdf.ApplyWatermark(watermark, rotation: 45, opacity: 70,
verticalAlignment: VerticalAlignment.Middle,
horizontalAlignment: HorizontalAlignment.Center);
pdf.SaveAs("watermarked_invoice.pdf");
}
}
using IronPdf;
using IronPdf.Editing;
License.LicenseKey = "IRONSUITE.WRITERS.21046-907F5E67CC-AHYQW6L-RCHLPMRJMU4G-SET72XAF2JNY-LQK45E5JPLGW-XOLPVBEBLHV7-2LHKZRWUZWMO-5LNIZSPF4BM6-UHUH4R-T4MMJ4MEIYSQEA-DEPLOYMENT.TRIAL-LDG2MK.TRIAL.EXPIRES.16.NOV.2025";
var pdf = new IronPdf.PdfDocument("invoice.pdf");
string content = pdf.ExtractAllText();
var lines = content.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
if (string.Equals(line.Trim(), "DRAFT", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("The document is a draft.");
// Corrected HTML and CSS
string watermark = @"<div style='color:red; font-size:72px; font-weight:bold;'>DRAFT</div>";
pdf.ApplyWatermark(watermark, rotation: 45, opacity: 70,
verticalAlignment: VerticalAlignment.Middle,
horizontalAlignment: HorizontalAlignment.Center);
pdf.SaveAs("watermarked_invoice.pdf");
}
}
Imports Microsoft.VisualBasic
Imports IronPdf
Imports IronPdf.Editing
License.LicenseKey = "IRONSUITE.WRITERS.21046-907F5E67CC-AHYQW6L-RCHLPMRJMU4G-SET72XAF2JNY-LQK45E5JPLGW-XOLPVBEBLHV7-2LHKZRWUZWMO-5LNIZSPF4BM6-UHUH4R-T4MMJ4MEIYSQEA-DEPLOYMENT.TRIAL-LDG2MK.TRIAL.EXPIRES.16.NOV.2025"
Dim pdf = New IronPdf.PdfDocument("invoice.pdf")
Dim content As String = pdf.ExtractAllText()
Dim lines = content.Split( { ControlChars.Cr, ControlChars.Lf }, StringSplitOptions.RemoveEmptyEntries)
For Each line In lines
If String.Equals(line.Trim(), "DRAFT", StringComparison.OrdinalIgnoreCase) Then
Console.WriteLine("The document is a draft.")
' Corrected HTML and CSS
Dim watermark As String = "<div style='color:red; font-size:72px; font-weight:bold;'>DRAFT</div>"
pdf.ApplyWatermark(watermark, rotation:= 45, opacity:= 70, verticalAlignment:= VerticalAlignment.Middle, horizontalAlignment:= HorizontalAlignment.Center)
pdf.SaveAs("watermarked_invoice.pdf")
End If
Next line
By using string.Equals, we are able to check whether the input PDF document contains the text marking it as a draft, and if it is, the program will apply our "DRAFT" watermark onto the document and save it.
Output
Best Practices for Using string.Equals with IronPDF
Always specify a StringComparison, this avoids bugs due to culture or case differences.
Use Trim() or Normalize() when comparing user-inputted or extracted text.
For large documents, extract only the necessary page or segment to reduce overhead.
- Combine string.Equals with Regex or Contains for hybrid string matching strategies.
Why IronPDF Makes It Easy
IronPDF streamlines the way developers interact with PDFs. Combined with C#'s string.Equals, it empowers you to build dynamic, intelligent PDF workflows without boilerplate or third-party tools.
Key Benefits of IronPDF:
Full text extraction and parsing.
Easy access to metadata.
Conditional manipulation with native C# logic.
- No need for external dependencies like Adobe or MS Office.
Deep Dive into StringComparison Options
When comparing strings in C#, the choice of StringComparison option can greatly affect the behavior and performance of your comparisons. Here's a quick overview of the most commonly used options:
Ordinal: Performs a fast, byte-by-byte comparison that is case-sensitive and culture-insensitive. Best for exact matches where culture doesn't matter.
OrdinalIgnoreCase: Same as above but ignores case differences. Ideal for scenarios like PDF text extraction where case inconsistencies can occur.
CurrentCulture: Considers cultural rules of the environment where the code runs. Useful when comparing user-facing text that should respect local language norms. Take into account the current culture, useful for localized string comparison.
CurrentCultureIgnoreCase: Same as above but ignores case.
- InvariantCulture and InvariantCultureIgnoreCase: Provide a consistent comparison across cultures, which is crucial for string equality in globalized apps..
Choosing the correct option ensures your string comparisons behave predictably. For PDF text extracted via IronPDF, OrdinalIgnoreCase is often the best choice, balancing performance and usability.
Performance Considerations for Large PDF documents
Handling large PDFs efficiently is key to maintaining responsive applications. Here are some tips:
Extract text from specific pages rather than the entire file.
Cache extracted text when processing the same document multiple times.
Use string.Equals for exact equality checks and Contains for substring matches, avoiding expensive regex operations when possible.
Utilize asynchronous processing or parallelization to handle multiple PDFs concurrently.
- Clean and normalize strings (string str1, string str2) before comparison to avoid false mismatches caused by invisible characters or formatting.
Implementing these techniques helps your PDF workflows scale gracefully while keeping comparisons accurate.
Error Handling and Debugging Tips
To avoid runtime issues and ensure reliability:
Guard against null values to prevent null reference exception by checking if object obj or strings are null before comparing.
Log extracted content to verify what the method returns during runtime.
Use Trim() and normalization to handle trailing spaces and special Unicode characters.
Include exception handling around PDF loading and text extraction.
- Write unit tests that cover various input scenarios, including case sensitive and case insensitive comparisons.
Final Thoughts
C# string.Equals is a simple yet powerful method that becomes even more effective when used with IronPDF’s robust PDF features. Whether you're verifying metadata, validating extracted text, or applying conditional logic, this combination gives you full control over your PDF automation workflows in .NET.
🔗 Get Started with IronPDF Today
Ready to start building intelligent PDF workflows with C#? Download the IronPDF NuGet package and explore the full power of .NET PDF generation, editing, and extraction.