C# – Filter a dictionary

The simplest way to filter a dictionary is by using the Linq Where() + ToDictionary() methods. Here’s an example: Note: You can use the Dictionary constructor (new Dictionary<string, int>(filterList)) instead of ToDictionary() if you prefer. This produces a new dictionary with the filtered item: Where() produces a list (actually an IEnumerable) of KeyValuePair objects. Most … Read more

C# – How to get the status code when using HttpClient

When you use HttpClient to make requests, you can directly get the status code from the HttpResponseMessage object, like this: The main reason for checking the status code is to determine if the request was successful and then reacting to error status codes (usually by throwing an exception). The HttpResponseMessage class has two helpers that … Read more

Moq – Verifying parameters passed to a mocked method

When you need to verify that the code under test called a method with the expected parameters, you can mock the method with Moq and use Verify() + It.Is<T>() to check the parameters passed in. Verify() asserts that the method call happened as expected with the specified parameters. Here’s an example. This is verifying that … 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

C# – Cannot use a lambda expression as an argument to a dynamically dispatched operation

Problem You are trying to use a lambda expression on a dynamic object and get the following compiler error: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. As an example, the following code causes this error: Solution Cast the … Read more

C# – How to unit test code that uses HttpClient

When you want to unit test code that uses HttpClient, you’ll want to treat HttpClient like any other dependency: pass it into the code (aka dependency injection) and then mock it out in the unit tests. There are two approaches to mocking it out: In this article I’ll show examples of these two approaches. Untested … Read more