I have a C# method declared like so:
public void Process<K, V>(params KeyValuePair<K, V>[] items)
{
...
}
Usage of this method looks kind of ugly; for example:
Process(
new KeyValuePair("key", "value"),
new KeyValuePair(123, Guid.NewGuid())
);
In Kotlin, you can create pairs using the to
infix function; for example:
val pair1 = "key" to "value"
val pair2 = 123 to UUID.randomUUID()
So the equivalent method usage looks a little tidier; for example:
process("key" to "value", 123 to UUID.randomUUID())
C# doesn't have infix functions, but something nearly equivalent could be achieved with extension methods; for example:
public static KeyValuePair<K, V> To<K, V>(this K key, V value) where K : notnull
{
return new KeyValuePair(key, value);
}
var pair1 = "key".To("value");
var pair2 = 123.To(Guid.NewGuid());
Process("key".To("value"), 123.To(Guid.NewGuid()));
That doesn't seem like the most elegant solution, so the other thing I was considering was that C# has dictionary initializer syntax; for example:
new Dictionary<object, object>()
{
["key"] = "value",
[123] = Guid.NewGuid()
}
or
new Dictionary<object, object>()
{
{ "key", "value" },
{ 123, Guid.NewGuid() }
}
So I was wondering whether dictionary initializer syntax could be applied to a method parameter; for example:
Process({ ["key"] = "value", [123] = Guid.NewGuid() });
or
Process({{ "key", "value" }, { 123, Guid.NewGuid() }});
Questions
Is dictionary initializer syntax as a method parameter possible, or is it syntactic sugar provided by the compiler when using a dictionary?
Are there any other elegant ways to create params
of KeyValuePair<K, V>
?