jstedfast/MailKit · error · ArgumentNullException

ArgumentNullException

Error message

ArgumentNullException

What it means

Guard in HeaderSet.Add: the 'header' argument was null. Adding a null Header to the set is invalid (and would corrupt the set contents), so it is rejected with ArgumentNullException; a read-only set would instead raise InvalidOperationException.

Solutions

  1. Null-check the header name before calling Add
  2. Use string.IsNullOrWhiteSpace guards when building the list
  3. Skip null entries instead of adding them

Example fix

// before
set.Add (headers["Custom"]); // may be null
// after
if (headers.TryGetValue ("Custom", out var name) && name != null)
    set.Add (name);
Defensive patterns

Strategy: validation

Validate before calling

if (!string.IsNullOrEmpty (header))
    set.Add (header);

Type guard

static bool IsValidHeaderInput (string s) => !string.IsNullOrWhiteSpace (s);

Try / catch

try {
    set.Add (header);
} catch (ArgumentNullException ex) {
    logger.LogWarning ("Skipped null header name: {Param}", ex.ParamName);
}

Prevention

When it happens

Trigger: Calling Add(null), often when the header name came from a dictionary lookup, config value, or variable that was never initialized.

Common situations: Building fetch/query header lists from dynamic config where an expected key is missing; passing results of string splitting that yielded null.

Related errors


AI-assisted analysis of jstedfast/MailKit@9d3859a785 (2026-09-15). Data as JSON: /api/errors/0f98eb2f7d78c120. Report an issue: GitHub.

Appendix: source

Thrown at MailKit/HeaderSet.cs:227

		/// <summary>
		/// Add the specified header.
		/// </summary>
		/// <remarks>
		/// Adds the specified header to the set of headers.
		/// </remarks>
		/// <returns><see langword="true" /> if the header was added to the set; otherwise, <see langword="false" />.</returns>
		/// <param name="header">The header to add.</param>
		/// <exception cref="ArgumentNullException">
		/// <paramref name="header"/> is <see langword="null" />.
		/// </exception>
		/// <exception cref="InvalidOperationException">
		/// The operation is invalid because the <see cref="HeaderSet"/> is read-only.
		/// </exception>
		public bool Add (string header)
		{
			if (header == null)
				throw new ArgumentNullException (nameof (header));

			if (!IsValid (header))
				throw new ArgumentException ("The header field is invalid.", nameof (header));

			CheckReadOnly ();

			return hash.Add (header.ToUpperInvariant ());
		}

		/// <summary>
		/// Add the specified header.
		/// </summary>
		/// <remarks>
		/// Adds the specified header to the set of headers.
		/// </remarks>
		/// <param name="item">The header to add.</param>
		/// <exception cref="ArgumentNullException">
		/// <paramref name="item"/> is <see langword="null" />.

View on GitHub (pinned to 9d3859a785)