Free Web Development Online Tutorials, Learn to Code
C# dictionary example, declare a dictionary c#, c# dictionary get value by key

C# Dictionary Examples

Dictionary is a collection object just like list object; in dictionary object, we can store values with key value pair, in this tutorial you will learn how to use C# Dictionary class with examples

C# Dictionary, initialize Dictionary Object

Here you learn C# Dictionary , IDictionary today, to access this object you need use the namespace System.Collections.Generic

C# Dictionary has no different meaning than English Dictionary word, it has exact same meaning, In C# Dictionary we can store information with key, value combination, and retrieve the value using the key.

Before we see some C# Dictionary Example, let’s look at some of the Important Properties

C# Dictionary Methods

Some commonly used dictionary methods.

  • Add

    Add key-value pairs <TKey, TValue> in Dictionary collection.

  • Add

    Adds an item with a key and value into the Dictionary.

  • TryGetValue

    Returns true and specified key assigns value in (out) parameter, if key does not exists then return false.

  • ContainsKey

    Checks whether the specified key (integer) exists in Dictionary object collection

  • Contains

    Checks whether the specified KeyValuePair exists in Dictionary <TKey, TValue>

C# Dictionary Example

Note: While adding in Dictionary object, you cannot add duplicate or null keys in Dictionary C#, though values can be duplicated or set as null, but Keys must be unique otherwise it will throw runtime exception.

using System.Collections.Generic;
IDictionary<int, string> _dictObj = new Dictionary<int, string>();
_dictObj.Add(1, "C# Dictionary Example");
_dictObj.Add(2, "Learning C# .Net");
_dictObj.Add(3, "Learning SQL Database");
_dictObj.Add(4, "Learning ASP.Net");
Retrieve value from C# Dictionary object Example

Two ways you can retrieve value from Dictionary object.

  • To retrieve single value from C# Dictionary object using key

    If the specified key does not exist then it will throw KeyNotFoundException.

  • To retrieve all values from Dictionary object using keys-collection
    for (int i = 0; i < _dictObj.Count; i++)
        Console.WriteLine("Key: {0}  Value: {1}", _dictObj.Keys.ElementAt(i), _dictObj[_dictObj.Keys.ElementAt(i)]);

TryGetValue in Dictionary C# Example

Suppose we are trying to find index 4 in above dictionary object using TryGetValue method

string _valueResult;             
if (_dictObj.TryGetValue(4, out _valueResult))
    Console.WriteLine("Specified key not found.");

Contains in Dictionary C#

Contains method will check if KeyValuePair is found in collection, returns true or false

_dictObj.Contains(new KeyValuePair<int, string>(1, "C# Dictionary Example"));
free C# tutorial online

C# Dictionary Example
Other Online Tutorial

C# .net Interview Questions Answers

.Net C# Examples | Join .Net C# Course