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<String, object>[] 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.
The KeyValuePair class stores a pair of values in a single list with C#. Set KeyValuePair and add elements − var myList = new List<KeyValuePair<string, int>>(); // adding elements myList. Add(new KeyValuePair<string, int>("Laptop", 20)); myList. Add(new KeyValuePair<string, int>("Desktop", 40)); myList.
A key-value pair (KVP) is a set of two linked data items: a key, which is a unique identifier for some item of data, and the value, which is either the data that is identified or a pointer to the location of that data. Key-value pairs are frequently used in lookup tables, hash tables and configuration files.
Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well. Simple Array eg. We see above that we can loop a numerical array using the jQuery.
When the syntax is bad for an otherwise decent pattern, change the syntax. How about:
public void MyFunction(params KeyValuePair<string, object>[] pairs) { // ... } public static class Pairing { public static KeyValuePair<string, object> Of(string key, object value) { return new KeyValuePair<string, object>(key, value); } }
Usage:
MyFunction(Pairing.Of("Key1", 5), Pairing.Of("Key2", someObject));
Even more interesting would be to add an extension method to string
to make it pairable:
public static KeyValuePair<string, object> PairedWith(this string key, object value) { return new KeyValuePair<string, object>(key, value); }
Usage:
MyFunction("Key1".PairedWith(5), "Key2".PairedWith(someObject));
Edit: You can also use the dictionary syntax without the generic brackets by deriving from Dictionary<,>
:
public void MyFunction(MessageArgs args) { // ... } public class MessageArgs : Dictionary<string, object> {}
Usage:
MyFunction(new MessageArgs { { "Key1", 5 }, { "Key2", someObject } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With