Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Literal notation for Dictionary in C#?

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 / Dictionarys in C#?

like image 520
pimvdb Avatar asked Feb 12 '11 20:02

pimvdb


People also ask

How dictionary works 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.

Is key unique in dictionary c#?

[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<> .


1 Answers

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.

like image 156
BoltClock Avatar answered Oct 11 '22 09:10

BoltClock