Skip to content

Hreflang Tag Generator — C# source

Turn a list of language versions into a valid hreflang set — locale normalization, duplicate detection and x-default handling — emitted as HTML link tags or an XML sitemap block.

This is the C# implementation — the same logic the interactive tool runs, in a shareable, citable form.

// hreflang-tag-generator — pure locale-list validation + alternate-link
// emission (SEO/meta trio).
//
// Language: C# (.NET 8), standard library only (no external packages — the
// hreflang grammar is pure, so unlike pdf-split's PDFsharp reference nothing
// display-only needs to be linked)
// CosmoDev polyglot showcase port of the `hreflang-tag-generator` tool.
// Ported from src/lib/hreflang.ts — display source, part of CosmoDev's
// polyglot tool pages. Mirrors this dir's java.java structure 1:1.

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace CosmoDev.HreflangTagGenerator;

/// <summary>One locale/URL pair. Mirrors the TS HreflangRow interface.</summary>
public sealed record HreflangRow(string Locale, string Url);

/// <summary>The field set for BuildHreflang — rows plus an optional x-default URL.</summary>
public sealed record HreflangInput(IReadOnlyList<HreflangRow> Rows, string? XDefaultUrl = null)
{
    /// <summary>The TS shape with rows omitted entirely: no rows, no x-default.</summary>
    public static readonly HreflangInput Empty = new(Array.Empty<HreflangRow>());
}

/// <summary>Diagnostics plus both emitted flavors. On failure Ok is false,
/// Errors lists every row-located problem, and Normalized/Html/Sitemap are
/// empty — exactly like the TS result.</summary>
public sealed record HreflangResult(
    bool Ok,
    IReadOnlyList<string> Errors,
    IReadOnlyList<HreflangRow> Normalized,
    string Html,
    string Sitemap);

/// <summary>The C# twin of the TS hreflang lib (all members static, like java.java).</summary>
public static class HreflangTagGenerator
{
    private static readonly Regex SingleLocale = new(@"^([a-zA-Z]{2})$", RegexOptions.Compiled);
    private static readonly Regex RegionLocale = new(@"^([a-zA-Z]{2})-([a-zA-Z]{2})$", RegexOptions.Compiled);
    private static readonly Regex ValidUrlRe = new(@"^https?://", RegexOptions.Compiled);

    /// <summary>Normalize a locale tag to Google's hreflang grammar: ll
    /// (ISO-639-1, lowercase) or ll-CC (region uppercase, ISO-3166). Case and
    /// surrounding whitespace are corrected (en-us -> en-US); anything else is
    /// invalid and returns null. The C# twin of normalizeLocale() in
    /// src/lib/hreflang.ts — null stands in for the TS null.</summary>
    public static string? NormalizeLocale(string raw)
    {
        var t = raw.Trim();
        var single = SingleLocale.Match(t);
        if (single.Success) return single.Groups[1].Value.ToLowerInvariant();
        var region = RegionLocale.Match(t);
        if (region.Success)
        {
            return region.Groups[1].Value.ToLowerInvariant() + "-" +
                   region.Groups[2].Value.ToUpperInvariant();
        }
        return null;
    }

    /// <summary>Trim raw and return it when it starts with http:// or https://,
    /// otherwise null. Mirrors the TS validUrl() helper.</summary>
    private static string? ValidUrl(string raw)
    {
        var t = raw.Trim();
        return ValidUrlRe.IsMatch(t) ? t : null;
    }

    /// <summary>Validate a locale/URL table and emit both hreflang flavors.
    /// Invalid input collects every error (row-located) and emits empty blocks;
    /// valid input normalizes locales, preserves row order, and appends
    /// x-default last.</summary>
    public static HreflangResult BuildHreflang(HreflangInput input)
    {
        var errors = new List<string>();
        var normalized = new List<HreflangRow>();
        var seen = new HashSet<string>();

        for (var i = 0; i < input.Rows.Count; i++)
        {
            var n = i + 1;
            var row = input.Rows[i];
            var rawLocale = row.Locale ?? "";
            var locale = NormalizeLocale(rawLocale);
            if (locale is null)
            {
                errors.Add($"Row {n}: \"{rawLocale.Trim()}\" is not a valid locale — use ll or ll-CC (e.g. en, de-AT).");
                continue;
            }
            if (seen.Contains(locale))
            {
                errors.Add($"Row {n}: locale \"{locale}\" is already used.");
                continue;
            }
            if (row.Url is null || row.Url.Trim().Length == 0)
            {
                errors.Add($"Row {n}: URL is required.");
                continue;
            }
            var url = ValidUrl(row.Url);
            if (url is null)
            {
                errors.Add($"Row {n}: URL must start with http:// or https://.");
                continue;
            }
            seen.Add(locale);
            normalized.Add(new HreflangRow(locale, url));
        }

        string? xDefault = null;
        if (input.XDefaultUrl is not null && input.XDefaultUrl.Trim().Length > 0)
        {
            xDefault = ValidUrl(input.XDefaultUrl);
            if (xDefault is null)
            {
                errors.Add("x-default: URL must start with http:// or https://.");
            }
        }

        if (errors.Count > 0)
        {
            return new HreflangResult(false, errors, Array.Empty<HreflangRow>(), "", "");
        }

        var htmlLines = new List<string>();
        var sitemapLines = new List<string>();
        foreach (var r in normalized)
        {
            htmlLines.Add($"<link rel=\"alternate\" href=\"{r.Url}\" hreflang=\"{r.Locale}\" />");
            sitemapLines.Add($"    <xhtml:link rel=\"alternate\" hreflang=\"{r.Locale}\" href=\"{r.Url}\"/>");
        }
        if (xDefault is not null)
        {
            htmlLines.Add($"<link rel=\"alternate\" href=\"{xDefault}\" hreflang=\"x-default\" />");
            sitemapLines.Add($"    <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\"{xDefault}\"/>");
        }

        return new HreflangResult(
            true,
            Array.Empty<string>(),
            normalized,
            string.Join("\n", htmlLines),
            string.Join("\n", sitemapLines));
    }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →