Skip to content

Instantly share code, notes, and snippets.

@SteffenBlake
Created June 28, 2025 18:37
Show Gist options
  • Select an option

  • Save SteffenBlake/997925b6ea2abebbee60e54cfa1924f1 to your computer and use it in GitHub Desktop.

Select an option

Save SteffenBlake/997925b6ea2abebbee60e54cfa1924f1 to your computer and use it in GitHub Desktop.
using System.Globalization;
using System.Runtime.CompilerServices;
Handler<string, int, string, DateTime, bool> SomeCommand =
(arg1, arg2, arg3, arg4, arg5, remainder) =>
{
Console.WriteLine(arg1);
Console.WriteLine(arg2);
Console.WriteLine(arg3);
Console.WriteLine(arg4);
Console.WriteLine(arg5);
Console.WriteLine(string.Join(',', remainder));
};
var rawInput = "/SomeCommand hello 1 world 2024-01-01 true remaining args here";
Dictionary<string, Action<ReadOnlySpan<string?>>> handlers = [];
RegisterHandler(SomeCommand);
var data = rawInput.Split(' ');
var commandNameRaw = data[0];
var arguments = data[1..];
if (!commandNameRaw.StartsWith('/'))
{
return;
}
var commandName = commandNameRaw[1..].ToLower();
if (!handlers.TryGetValue(commandName, out var handler))
{
return;
}
handler(arguments);
void RegisterHandler<T1, T2, T3, T4, T5>(
Handler<T1, T2, T3, T4, T5> handler,
[CallerArgumentExpression(nameof(handler))]
string? handlerName = null
)
where T1 : IParsable<T1>
where T2 : IParsable<T2>
where T3 : IParsable<T3>
where T4 : IParsable<T4>
where T5 : IParsable<T5>
{
var handlerNameInternal = handlerName?.ToLower() ??
throw new ArgumentNullException(nameof(handlerName));
handlers[handlerNameInternal] = (input) =>
{
handler(
T1.Parse(input[0] ?? "", CultureInfo.InvariantCulture),
T2.Parse(input[1] ?? "", CultureInfo.InvariantCulture),
T3.Parse(input[2] ?? "", CultureInfo.InvariantCulture),
T4.Parse(input[3] ?? "", CultureInfo.InvariantCulture),
T5.Parse(input[4] ?? "", CultureInfo.InvariantCulture),
input[5..]
);
};
}
delegate void Handler<T1, T2, T3, T4, T5>(
T1 a, T2 b, T3 c, T4 d, T5 e, ReadOnlySpan<string?> rem
)
where T1 : IParsable<T1>
where T2 : IParsable<T2>
where T3 : IParsable<T3>
where T4 : IParsable<T4>
where T5 : IParsable<T5>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment