Skip to content

AI Code Explainer — C# source

Paste any code snippet and get a plain-language explanation from an LLM — beginner, developer, or expert depth — with your own free Groq key, straight from your browser.

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

// code-explainer — language guessing, depth-graded prompts, reply cleanup.
//
// Language: C# (netstandard2.0 surface, standard library only —
//           System.Text.RegularExpressions.Regex with RegexOptions
//           .ECMAScript pins \w and \b to the ASCII semantics the TS
//           rules assume; Multiline and IgnoreCase mirror the /m and /i
//           flags)
// CosmoDev polyglot showcase port of the `code-explainer` tool, ported from
// src/lib/code-explainer.ts (the canonical TypeScript implementation).
//
// Why this file exists: the whole explainer pipeline is three pure functions
// — guess which language a paste is, wrap it in a depth-graded chat prompt,
// strip code fences from the reply — so every runtime runs the identical
// heuristics. C# strings are UTF-16, so the truncation slice at MaxCodeChars
// is unit-for-unit identical to the TS code.slice(0, n).
//
// display source — part of CosmoDev's polyglot tool pages.
//
// Build: csc csharp.cs && csharp.exe   (or drop into any .NET console app)

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

namespace CosmoDev.Polyglot
{
    /// <summary>One [system, user] chat message for the provider layer.</summary>
    public sealed class ChatMessage
    {
        public ChatMessage(string role, string content)
        {
            Role = role;
            Content = content;
        }

        public string Role { get; }
        public string Content { get; }
    }

    /// <summary>code-explainer — pure logic, no I/O.</summary>
    public static class CodeExplainer
    {
        /// <summary>Guess the language from (and prompt with) at most this many chars.</summary>
        public const int MaxCodeChars = 12000;

        /// <summary>Per-level explanation contract, verbatim from the TS lib.</summary>
        private static readonly Dictionary<string, string> LevelContract =
            new Dictionary<string, string>
            {
                ["beginner"] = "Explain for a smart newcomer: no unexplained jargon, short sentences, one everyday analogy if it helps. Say what it does first, then how, step by step.",
                ["developer"] = "Explain for a working developer: concise and practical. Lead with what it does, then the flow, the patterns used, and the pitfalls an editor should catch.",
                ["expert"] = "Explain for an expert: dense and precise. Cover invariants, complexity, edge cases, and anything subtle an experienced reviewer would flag.",
            };

        private sealed class Rule
        {
            public Rule(string lang, string pattern, RegexOptions options)
            {
                Lang = lang;
                Re = new Regex(pattern, options | RegexOptions.ECMAScript);
            }

            public string Lang { get; }
            public Regex Re { get; }
        }

        // Cheap keyword heuristics — enough to name the language in the
        // prompt so the model starts right; never a language detector.
        // First match wins, so order matters: go before rust before python
        // before the web trio.
        private static readonly Rule[] Rules =
        {
            new Rule("go", @"\bpackage\s+\w+|\bfunc\s+\w+|:=", RegexOptions.None),
            new Rule("rust", @"\bfn\s+\w+|\blet\s+mut\b|\bimpl\b", RegexOptions.None),
            new Rule("python", @"\bdef\s+\w+\s*\(|\bprint\s*\(|\bimport\s+\w+\s*$", RegexOptions.Multiline),
            new Rule("sql", @"\bSELECT\b.+\bFROM\b", RegexOptions.IgnoreCase),
            new Rule("typescript", @"\binterface\s+\w+\s*\{|\btype\s+\w+\s*=|:\s*(string|number|boolean)\b", RegexOptions.None),
            new Rule("javascript", @"\bconst\s+\w+\s*=|=>|console\.log", RegexOptions.None),
            new Rule("css", @"[.#]?[\w-]+\s*\{[^}]*:[^}]*;", RegexOptions.None),
            new Rule("html", @"</?[a-z][\w-]*(\s+[\w-]+=""[^""]*"")*\s*/?>", RegexOptions.IgnoreCase),
        };

        /// <summary>
        /// Guess which language a code sample is written in. Falls back to
        /// "text" when no rule matches, so the prompt can tell the model to
        /// reason about the paste as pseudocode. Twin of guessLanguage() in
        /// src/lib/code-explainer.ts.
        /// </summary>
        public static string GuessLanguage(string code)
        {
            foreach (Rule rule in Rules)
            {
                if (rule.Re.IsMatch(code)) return rule.Lang;
            }
            return "text";
        }

        /// <summary>
        /// Build the [system, user] chat messages for the provider layer.
        /// The code is truncated BEFORE guessing: the heuristics only need a
        /// sample. Twin of buildPromptMessages() in src/lib/code-explainer.ts.
        /// </summary>
        public static IList<ChatMessage> BuildPromptMessages(string code, string level)
        {
            LevelContract.TryGetValue(level, out string contract);
            bool truncated = code.Length > MaxCodeChars;
            string body = truncated
                ? code.Substring(0, MaxCodeChars) + "\n… (code truncated)"
                : code;
            string lang = GuessLanguage(body);
            string uncertainty = lang == "text"
                ? " (no clear language — say so and reason about it as pseudocode)"
                : "";
            return new ChatMessage[]
            {
                new ChatMessage(
                    "system",
                    $"You explain code. {contract} The code appears to be {lang}{uncertainty}. "
                    + "Use short paragraphs or bullets; markdown is fine."),
                new ChatMessage("user", body),
            };
        }

        /// <summary>Strips ``` fences, with their optional language tag and
        /// newline (TS: /```[a-z]*\n?/g).</summary>
        private static readonly Regex Fence =
            new Regex(@"```[a-z]*\n?", RegexOptions.ECMAScript);

        /// <summary>
        /// Clean the model's reply into displayable explanation text: strip
        /// markdown code fences, then trim. Returns null only when nothing
        /// survives cleaning. Twin of parseExplanation() in the TS lib.
        /// </summary>
        public static string ParseExplanation(string text)
        {
            string cleaned = Fence.Replace(text, string.Empty).Trim();
            return cleaned.Length > 0 ? cleaned : null;
        }

        private static void Main()
        {
            Console.WriteLine(GuessLanguage("package main\nfunc main() {}")); // go
            Console.WriteLine(GuessLanguage("def hi():\n    print(hi())"));   // python
            Console.WriteLine(GuessLanguage("SELECT id FROM users"));         // sql
            Console.WriteLine(GuessLanguage("plain thoughts"));               // text

            foreach (ChatMessage message in BuildPromptMessages("x = 1", "expert"))
            {
                Console.WriteLine($"{message.Role}: {message.Content}");
            }

            Console.WriteLine(ParseExplanation("```python\nprint('hi')\n```\nIt prints!"));
            Console.WriteLine(ParseExplanation("```\n```") ?? "(null)");
        }
    }
}

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 →