create a dictionary in csharp

In C#, a dictionary is a common data structure used to store key-value pairs. To create a dictionary in C#, follow these steps:

  1. Import the System.Collections.Generic namespace, which contains the Dictionary class.
main.cs
using System.Collections.Generic;
34 chars
2 lines
  1. Declare a Dictionary variable, specifying the data types for the keys and values.
main.cs
Dictionary<string, int> myDictionary;
38 chars
2 lines

In this example, the keys are strings and the values are integers.

  1. Instantiate the dictionary using the constructor.
main.cs
myDictionary = new Dictionary<string, int>();
46 chars
2 lines
  1. Add key-value pairs to the dictionary using the Add() method.
main.cs
myDictionary.Add("apple", 5);
myDictionary.Add("banana", 2);
myDictionary.Add("pear", 3);
90 chars
4 lines
  1. Access a value in the dictionary by specifying its key using the indexer.
main.cs
int appleCount = myDictionary["apple"];
40 chars
2 lines

In this example, the appleCount variable will have the value of 5.

Here's the full code:

main.cs
using System.Collections.Generic;

Dictionary<string, int> myDictionary;
myDictionary = new Dictionary<string, int>();

myDictionary.Add("apple", 5);
myDictionary.Add("banana", 2);
myDictionary.Add("pear", 3);

int appleCount = myDictionary["apple"]; // appleCount is 5
270 chars
11 lines

gistlibby LogSnag