Project · Runtime

Metadata-to-delegate routing lab

Discover a bounded set of annotated static methods, validate signatures, create real typed delegates, and run six console contract checks. No plugin loading or test framework is implied.

All C# source files below are loaded together in the playground. Files written by a run live in its virtual directory.

Program.cs

var checks = RouterChecks.Run();
foreach (var check in checks) Console.WriteLine($"{check.Name}:{(check.Passed ? "PASS" : "FAIL")}");
Console.WriteLine($"passed:{checks.Count(check => check.Passed)}/{checks.Count}");
return checks.All(check => check.Passed) ? 0 : 1;

Metadata/OperationAttribute.cs

[AttributeUsage(AttributeTargets.Method)]
public sealed class OperationAttribute : Attribute
{
    public static int Constructions;
    public string Name { get; }
    public OperationAttribute(string name) { Name = name; Constructions++; }
}

Domain/Operations.cs

public static class Operations
{
    [Operation("double")] public static int Double(int value) => checked(value * 2);
    [Operation("positive")] public static int Positive(int value) => value > 0 ? value : throw new ArgumentOutOfRangeException(nameof(value));
}

Runtime/OperationRouter.cs

using System.Reflection;
public sealed class OperationRouter
{
    private readonly Dictionary<string, Func<int, int>> routes = new(StringComparer.Ordinal);
    public IReadOnlyList<string> Names => routes.Keys.OrderBy(name => name, StringComparer.Ordinal).ToArray();
    public OperationRouter(Type container)
    {
        foreach (var method in container.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly))
        {
            var metadata = CustomAttributeData.GetCustomAttributes(method).SingleOrDefault(item => item.AttributeType == typeof(OperationAttribute));
            if (metadata is null) continue;
            string name = (string)metadata.ConstructorArguments[0].Value!;
            var parameters = method.GetParameters();
            if (string.IsNullOrWhiteSpace(name) || method.ContainsGenericParameters || method.ReturnType != typeof(int) || parameters.Length != 1 || parameters[0].ParameterType != typeof(int))
                throw new InvalidOperationException("Unsupported operation signature");
            if (!routes.TryAdd(name, method.CreateDelegate<Func<int, int>>())) throw new InvalidOperationException("Duplicate operation");
        }
    }
    public bool TryInvoke(string name, int input, out int output)
    {
        if (!routes.TryGetValue(name, out var operation)) { output = 0; return false; }
        output = operation(input); return true;
    }
}

Checks/RouterChecks.cs

public static class RouterChecks
{
    public static List<(string Name, bool Passed)> Run()
    {
        var router = new OperationRouter(typeof(Operations));
        List<(string Name, bool Passed)> checks = [];
        checks.Add(("double", router.TryInvoke("double", 3, out int doubled) && doubled == 6));
        checks.Add(("missing", !router.TryInvoke("other", 3, out int missing) && missing == 0));
        bool domain = false;
        try { router.TryInvoke("positive", 0, out _); } catch (ArgumentOutOfRangeException) { domain = true; }
        checks.Add(("domain-error", domain));
        checks.Add(("metadata-only", OperationAttribute.Constructions == 0));
        checks.Add(("sorted-names", router.Names.SequenceEqual(new[] { "double", "positive" })));
        bool overflow = false;
        try { router.TryInvoke("double", int.MaxValue, out _); } catch (OverflowException) { overflow = true; }
        checks.Add(("overflow", overflow));
        return checks;
    }
}

ConsoleLab.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <LangVersion>13.0</LangVersion>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>