I currently have a WebSocket between JavaScript and a server programmed in C#. In JavaScript, I can pass data easily using an associative array:
var data = {'test': 'val', 'test2': 'val2'};
To represent this data object on the server side, I use a Dictionary<string, string>
, but this is more 'typing-expensive' than in JavaScript:
Dictionary<string, string> data = new Dictionary<string,string>(); data.Add("test", "val"); data.Add("test2", "val2");
Is there some kind of literal notation for associative arrays / Dictionary
s in C#?
A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take more memory because for each value there is also a key.
[C#] Dictionary with duplicate keysThe Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .
You use the collection initializer syntax, but you still need to make a new Dictionary<string, string>
object first as the shortcut syntax is translated to a bunch of Add()
calls (like your code):
var data = new Dictionary<string, string> { { "test", "val" }, { "test2", "val2" } };
In C# 6, you now have the option of using a more intuitive syntax with Dictionary as well as any other type that supports indexers. The above statement can be rewritten as:
var data = new Dictionary<string, string> { ["test"] = "val", ["test2"] = "val2" };
Unlike collection initializers, this invokes the indexer setter under the hood, rather than an appropriate Add()
method.
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