C# Development with Dictionaries
TL;DR
The Dictionary<TKey, TValue>
in C# is ideal for fast, structured data access, making it essential for document workflows like PDF forms, OCR, and HTML conversions in GdPicture.NET. Use TryGetValue
instead of ContainsKey
to safely retrieve values in one efficient step. GdPicture.NET natively supports dictionaries for cookies, headers, and OCR configurations—allowing dynamic, scalable automation.
C# is a powerful language, especially when working with structured data in document processing applications. One of the key data structures you’ll encounter is the Dictionary<TKey, TValue>
, a collection that maps keys to values and offers fast lookups.
Let’s explore how Dictionary
works in C#, why TryGetValue
is preferred over other methods, and how you can use it efficiently with GdPicture.NET SDK components like PDF form processing, OCR, and web content conversion.
Understanding the Basics of C# Dictionary
A Dictionary is a collection of key/value pairs where each key is unique. This structure is commonly used in document workflows to map:
- Field names to values in a PDF form
- OCR language settings
- HTTP headers or cookies for HTML conversion
Here’s an example using a Dictionary to store form fields:
Dictionary<string, string> formFields = new Dictionary<string, string>
{
{ "FirstName", "Alice" },
{ "LastName", "Smith" },
{ "Email", "alice@example.com" }
};
This allows you to quickly access values by their keys, such as retrieving "FirstName"
or checking if "Email"
is available.
The Conventional Approach: ContainsKey Method
When working with dictionaries, one common task is retrieving a value based on a key. But accessing a non-existent key directly can throw a KeyNotFoundException
. To avoid this, developers often use the ContainsKey
method to check for the key’s existence:
string key = "FirstName";
if (formFields.ContainsKey(key))
{
string name = formFields[key];
Console.WriteLine($"Name: {name}");
}
else
{
Console.WriteLine("Key not found.");
}
This works, but there’s a caveat: you’re doing two operations—one to check the key, and another to retrieve its value.
Combining Verification and Retrieval with TryGetValue
This is where the TryGetValue
method comes in. It performs the check and value retrieval in a single operation, improving performance and simplifying the code.
Syntax:
Dictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value)
Here’s the same example using TryGetValue
:
if (formFields.TryGetValue("FirstName", out string name))
{
Console.WriteLine($"Name: {name}");
}
else
{
Console.WriteLine("Key not found.");
}
This is not only cleaner, but it also avoids redundant lookups—an advantage when processing large sets of fields or headers.
TryGetValue In Action: GdPicture.NET Example
Let’s apply this to a real-world use case using GdPicture.NET to extract form data from a PDF.
GdPicturePDF pdf = new GdPicturePDF();
pdf.LoadFromFile("contract.pdf", false);
Dictionary<string, string> fields = new Dictionary<string, string>();
foreach (var fieldName in pdf.GetFormFieldNames())
{
fields[fieldName] = pdf.GetFormFieldValue(fieldName);
}
// Retrieve a value safely using TryGetValue
if (fields.TryGetValue("Email", out string email))
{
Console.WriteLine($"Email: {email}");
}
else
{
Console.WriteLine("Email field not found.");
}
By using TryGetValue
, you avoid crashes and keep your code clean—even when working with dynamic PDF templates.
GdPicture.NET Dictionary Properties You Should Know
The GdPicture.NET SDK uses Dictionary<string, string>
natively in several components to simplify configuration and extend functionality.
1. HTMLCustomCookies Property
Allows you to pass cookies during HTML-to-PDF conversion. Perfect for authenticated sessions.
var converter = new GdPictureDocumentConverter();
converter.HTMLCustomCookies = new Dictionary<string, string>
{
{ "SessionID", "abc123" },
{ "Token", "secure-token" }
};
2. HTMLCustomHTTPHeaders Property
Enables custom headers (e.g., Authorization tokens) for HTML rendering.
converter.HTMLCustomHTTPHeaders = new Dictionary<string, string>
{
{ "Authorization", "Bearer xyz" },
{ "User-Agent", "GdPictureBot/1.0" }
};
🔗 HTMLCustomHTTPHeaders Reference
3. OCR Dictionary Settings
Several GdPicture OCR-related components support specifying the language dictionary as a string (like "eng"
, "fra"
), which guides recognition logic:
PdfOcrOptions.Dictionary
SmartRedactionOptions.Dictionary
GdPictureTextExtraction.Dictionary
XTractFlow.DocumentProcessor.Dictionary
Example:
var ocrOptions = new PdfOcrOptions
{
Dictionary = "eng" // Use English dictionary for better accuracy
};
These settings can be managed dynamically with Dictionary<string, string>
configurations per document type or user preference.
Real-World Scenario: Dynamic PDF Conversion with Headers and Cookies
Let’s bring it all together with a scenario: converting a secure web dashboard to PDF using custom headers and cookies stored in a dictionary.
var converter = new GdPictureDocumentConverter();
Dictionary<string, string> cookies = new Dictionary<string, string>
{
{ "Session", "abc123" },
{ "Locale", "en-US" }
};
Dictionary<string, string> headers = new Dictionary<string, string>
{
{ "Authorization", "Bearer 987token" }
};
converter.HTMLCustomCookies = cookies;
converter.HTMLCustomHTTPHeaders = headers;
converter.LoadFromHtml("https://secure.portal.com/dashboard");
converter.SaveAsPDF("dashboard.pdf");
You could also use TryGetValue
if you want to log or verify a specific cookie:
if (cookies.TryGetValue("Session", out string sessionID))
{
Console.WriteLine($"Using session: {sessionID}");
}
Conclusion
As we’ve seen, C#’s Dictionary
and its TryGetValue
method are incredibly useful in real-world document automation—especially with a robust toolkit like GdPicture.NET.
Whether you’re extracting form fields, injecting cookies into HTML renderers, or customizing OCR behavior, GdPicture’s use of dictionaries helps you write cleaner, safer, and more efficient code.
Explore more in the official GdPicture.NET documentation and start building smarter document workflows today.
FAQ
1. What is a C# Dictionary and why is it useful?
A Dictionary<TKey, TValue>
is a key-value pair collection in C# that allows fast lookups and structured data management. It’s commonly used for storing metadata, form fields, headers, or settings.
2. What is the difference between ContainsKey
and TryGetValue
?
ContainsKey
checks if a key exists, then you perform a second operation to retrieve the value.TryGetValue
does both in one step—more efficient and safer for large datasets.
3. How does GdPicture.NET use Dictionary in its SDK?
GdPicture.NET uses Dictionary<string, string>
in several areas, including:
HTMLCustomCookies
andHTMLCustomHTTPHeaders
for web content rendering- OCR-related components for language dictionaries (e.g.,
"eng"
,"fra"
) These integrations allow for customizable and dynamic document automation.
4. Can I use Dictionary with PDF forms in GdPicture.NET?
Yes! You can populate a Dictionary with field names and values from PDF forms using GdPicturePDF.GetFormFieldNames()
and GetFormFieldValue()
.
5. Is TryGetValue
supported in all .NET versions?
Yes, TryGetValue
has been available since .NET Framework 2.0 and is fully supported in .NET Core and .NET 6+.
Hulya is a frontend web developer and technical writer at GDPicture who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.
Tags: