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.
You can do that:
where DateField and IdField are supposed to be a 'string' identifiers.
The TestNameMethod:
Performance is 5% faster than using Dictionary. Disadvantage: you can't use variable as a key.
A bit of a hack, but you could have your
Message
class implement theIEnumerable
interface and give it anAdd
method. You'll then be able to use collection initializer syntax:You could also reference the nugetpackage "valuetuple", which allows you to do the following:
You can then call the method like this:
You could use Tuples to achieve something similar to @Bryan Watts's
Pairing.Of
without the extra class:Here's more of the same:
Some details on initialising a dictionary can be found here.