C# – Add to a dictionary

The simplest way to add a key/value pair to a dictionary is by using Dictionary.Add(), like this: If the key already exists, Dictionary.Add() throws an ArgumentException because the key must be unique. There are a few other ways to add to a dictionary in different scenarios, which I’ll explain below. Add or update key/value in … Read more

C# – Hex string to byte array

This article shows code for converting a hex string to a byte array, unit tests, and a speed comparison. First, this diagram shows the algorithm for converting a hex string to a byte array. To convert a hex string to a byte array, you need to loop through the hex string and convert two characters … Read more

KeyNotFoundException: The given key was not present in the dictionary

Problem The following exception is thrown when you try to get a value from a dictionary using a key that doesn’t exist in the dictionary: KeyNotFoundException: ‘The given key was not present in the dictionary.’ Consider the following the example of initializing a dictionary with a few key/value pairs, and then trying to access non-existent … Read more