I'm looking for a way to have a function such as:
myFunction({"Key", value}, {"Key2", value});
I'm sure there's something with anonymous types that would be pretty easy, but I'm not seeing it.
The only solution I can think of is to have a "params KeyValuePair[] pairs" parameter, but that ends up being something similar to:
myFunction(new KeyValuePair<String, object>("Key", value), new KeyValuePair<String, object>("Key2", value));
Which is, admittedly, much uglier.
EDIT:
To clarify, I'm writing a "Message" class to pass between 2 different systems. It contains a ushort specifying the the Message Type, and a dictionary of string to object for "Data" associated with the message. I'd like to be able to pass all this information in the constructor, so I am able to do this:
Agent.SendMessage(new Message(MessageTypes.SomethingHappened, "A", x, "B", y, "C", z)); or similar syntax.
Using a dictionary:
Which is straight forward, you need only one
new Dictionary<K, V>
, not for each argument. It's trivial to get the keys and values.Or with an anonymous type:
Which is not very nice to use inside the function, you'll need reflection. This would look something like this:
(Staight from my head, probably some errors...)
With dynamic type in C# 4.0:
Call using:
Since C# 7.0, you can use value tuples. C# 7.0 not only introduces a new type but a simplified syntax for tuple types as well as for tuple values.
It is also possible to deconstruct a tuple like this
This extracts the items of the tuple in two separate variables
key
andvalue
.Now, you can call
MyFunction
with a varying number of arguments easily:See: New Features in C# 7.0
When the syntax is bad for an otherwise decent pattern, change the syntax. How about:
Usage:
Even more interesting would be to add an extension method to
string
to make it pairable:Usage:
Edit: You can also use the dictionary syntax without the generic brackets by deriving from
Dictionary<,>
:Usage:
Funny, I just created (minutes ago) a method that allows to do that, using anonymous types and reflection :
Use a Dictionary ...