In C#, Convert.TryFromHexString attempts to decode hex characters into a destination byte span.
Returns false for odd length, illegal digits, or a too-small buffer—no FormatException.
This is a static member of System.Convert. You call it with the type name, such as Convert.TryFromHexString(...). Convert is the everyday API for converting between common CLR types in C#.
Syntax
Pass hex text and a destination byte span.
C#
Span<byte> dest = stackalloc byte[8];
bool ok = Convert.TryFromHexString("0A1B", dest, out int written);
Call
What it does
Convert.TryFromHexString(hex, dest, out written)
true when decode succeeds.
Newer .NET API. Prefer this for untrusted hex dumps.
Library declarations
C#
public static bool TryFromHexString(ReadOnlySpan<char> source,
Span<byte> destination, out int bytesWritten);
Parameters
Parameter
Description
source
Required. Hex characters.
destination
Required. Byte buffer.
bytesWritten
Out. Bytes written on success.
Return Value
Return Value
Description
true
Decode succeeded.
false
Invalid hex or buffer too small.
C# Examples
Example 1 — Decode Valid Hex
Try-decode 0A1B into a stack buffer.
C#
using System;
class Program {
static void Main() {
Span<byte> dest = stackalloc byte[8];
bool ok = Convert.TryFromHexString("0A1B", dest, out int written);
Console.WriteLine(ok);
Console.WriteLine(string.Join(",", dest.Slice(0, written).ToArray()));
}
}
Output
True
10,27
How It Works
Valid pairs. Four digits → two bytes.
ok true. Decode filled the span.
10,27. Decimal view of 0x0A and 0x1B.
Slice written. Ignore unused buffer tail.
Example 2 — False on Odd Digits
Reject a three-character hex string.
C#
using System;
class Program {
static void Main() {
Span<byte> dest = stackalloc byte[8];
bool ok = Convert.TryFromHexString("0A1", dest, out int written);
Console.WriteLine(ok);
Console.WriteLine(written);
}
}
Output
False
0
How It Works
Odd length. Hex must come in pairs.
false. Soft failure, no throw.
written 0. Do not read dest.
Validate first. Useful for pasted dumps.
Example 3 — Contrast FromHexString
Show Try success beside a throwing failure.
C#
using System;
class Program {
static void Main() {
Span<byte> dest = stackalloc byte[8];
Console.WriteLine(Convert.TryFromHexString("FF", dest, out _));
try {
Convert.FromHexString("ZZ");
} catch (FormatException) {
Console.WriteLine("threw");
}
}
}
Output
True
threw
How It Works
FF ok. Try decodes a valid byte.
ZZ illegal. FromHexString throws.
FormatException. Catch prints threw.
Choose Try. When bad hex is common.
Frequently Asked Questions
When hex text may be invalid or incomplete.
Return false (pairs required).
Need at least source.Length / 2 bytes.
TryToHexString writes hex into a char span.
May only have custom hex parsers—these APIs are modern .NET.