Skip to content

Instantly share code, notes, and snippets.

@npruehs npruehs/DictionaryDemo.cs
Last active Dec 7, 2015

What would you like to do?
Short example of how to use .NET Dictionaries.
// Create new dictionary.
Dictionary<Player, int> highscores = new Dictionary<Player, int>();
// Add some players.
var playerNick = new Player { Name = "Nick", Id = 1 };
var playerChristian = new Player { Name = "Christian", Id = 2 };
highscores.Add(playerNick, 33);
highscores.Add(playerChristian, 45);
// Print player count.
Console.WriteLine("There are {0} players with scores:", highscores.Count);
// Show all scores.
foreach (var nameWithScore in highscores)
Console.WriteLine("{0}: {1}", nameWithScore.Key, nameWithScore.Value);
// Get specific value.
Console.WriteLine("Nick has a score of {0}.", highscores[playerNick]);
// Safe way to get specific value.
int score;
if (highscores.TryGetValue(playerChristian, out score))
Console.WriteLine("Christian has a score of {0}.", score);
// Wait for key.
public class Player
#region Properties
public int Id { get; set; }
public string Name { get; set; }
#region Public Methods and Operators
public override string ToString()
return this.Name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.