Markdown Parser Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Markdown Parser runs in O(n) time and O(n) space, in C# as in every other language.
- ✓ReadOnlySpan<char> is the type this problem is shaped around in modern .NET: a slice is a reference and a length, allocating nothing, and MemoryExtensions.IndexOf over a span is always ordinal.
- ✓Write StringComparison.Ordinal out loud, everywhere. The analysers CA1307 and CA1310 exist because the culture-sensitive overloads are the defaults, and a parser has no business collating anything.
- ✓The C# trap: string.IndexOf(string) collates. Since .NET 5 switched string comparison to ICU, the string overload still defaults to the current culture, and ICU treats a carriage return followed by a line feed as a single collation element.
- ✓Spans delete the allocation a naive parser makes on every line. string.Substring always copies, whereas slicing a ReadOnlySpan<char> copies a struct of a reference and a length, so the block scanner can peel container markers off a line for nothing.
What Markdown Parser actually is
Markdown Parser in C#: what you actually reach for
C# implementation
using System;
using System.Globalization;
readonly record struct Run(int Start, int Length, char Marker, bool CanOpen, bool CanClose);
static class Delimiters
{
static bool Punct(char c) => CharUnicodeInfo.GetUnicodeCategory(c) is
UnicodeCategory.ConnectorPunctuation or UnicodeCategory.DashPunctuation or
UnicodeCategory.OpenPunctuation or UnicodeCategory.ClosePunctuation or
UnicodeCategory.InitialQuotePunctuation or UnicodeCategory.FinalQuotePunctuation or
UnicodeCategory.OtherPunctuation or UnicodeCategory.MathSymbol or
UnicodeCategory.CurrencySymbol or UnicodeCategory.ModifierSymbol or
UnicodeCategory.OtherSymbol;
// Slicing a span allocates nothing, and span searches are ordinal, unlike
// string.IndexOf(string), which collates under the current culture.
public static void Scan(ReadOnlySpan<char> text, Action<Run> emit)
{
for (int i = 0; i < text.Length;)
{
char c = text[i];
if (c != '*' && c != '_') { i++; continue; }
int end = i;
while (end < text.Length && text[end] == c) end++;
char before = i > 0 ? text[i - 1] : '\n';
char after = end < text.Length ? text[end] : '\n';
bool bw = char.IsWhiteSpace(before), aw = char.IsWhiteSpace(after);
bool bp = Punct(before), ap = Punct(after);
bool left = !aw && (!ap || bw || bp);
bool right = !bw && (!bp || aw || ap);
// an underscore may not open or close inside a word
emit(c == '*'
? new Run(i, end - i, c, left, right)
: new Run(i, end - i, c, left && (!right || bp), right && (!left || ap)));
i = end;
}
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Markdown Parser?
ReadOnlySpan<char> is the type this problem is shaped around in modern .NET: a slice is a reference and a length, allocating nothing, and MemoryExtensions.IndexOf over a span is always ordinal. Classification comes from System.Globalization.CharUnicodeInfo.GetUnicodeCategory and the UnicodeCategory enum, with System.Text.Rune and Rune.GetUnicodeCategory when a neighbour might be a surrogate pair. The base class library has no markdown parser; Markdig is the ecosystem answer, driven through MarkdownPipelineBuilder and Markdown.ToHtml, and extended by registering inline parsers against the characters that trigger them.
What is the most common C# mistake when implementing Markdown Parser?
string.IndexOf(string) collates. Since .NET 5 switched string comparison to ICU, the string overload still defaults to the current culture, and ICU treats a carriage return followed by a line feed as a single collation element. The documented consequence is that "Hello\r\nworld!".IndexOf("\n") returns -1, so a line splitter written the obvious way finds no line endings in a Windows-authored document and passes the entire file to the block parser as a single line. Soft hyphens and zero-width joiners are ignorable under the same collation, so a scan for the ]( of an inline link can match across them. The char overload and every span search are ordinal.
How does Markdown Parser actually perform in C#?
Spans delete the allocation a naive parser makes on every line. string.Substring always copies, whereas slicing a ReadOnlySpan<char> copies a struct of a reference and a length, so the block scanner can peel container markers off a line for nothing. The price is that a ref struct cannot be a class field, cannot be boxed and cannot cross an await, so the span scanner stays a synchronous inner loop with the tree assembled outside it. For output, ArrayPool<char>.Shared or string.Create avoids the gen-0 churn of a StringBuilder that keeps resizing. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.