Deserializing JSON that contains an embedded JSON string

When you send mail, you put a letter in an envelope and put routing information on the envelope. The postal service uses the routing information to deliver the envelope to a specific mailbox. The mailbox owner then opens the envelope and reads the letter. Sometimes you may need to deal with the JSON equivalent of … Read more

C# – How to unit test code that uses Dapper

Dapper makes your code difficult to unit test. The problem is that Dapper uses static extension methods, and static methods are difficult to mock out. One approach is to wrap the Dapper static methods in a class, extract out an interface for that wrapper class, and then dependency inject the wrapper interface. In the unit … Read more

C# – Default method implementations and constants in interfaces

Starting in C# 7, you can add default method implementations (and constants) to interfaces, like this: This outputs the following: Microsoft’s stated purpose for this feature is that it allows you add methods to an interface without breaking existing implementing classes. That’s nice, but it weakens the concept of interfaces (forcing implementers to adhere to … Read more

C# – How to check if a type has a default constructor

A default constructor is a constructor that doesn’t have parameters. Therefore, to check if a type has a default constructor, you can use reflection to loop through the constructors and see if there are any with no parameters, like this: In this article I’ll show an example of loading types that implement a specific interface … Read more

C# – How to unit test async methods

Let’s say you have the following async method you want to test: Here’s how to unit test this: This is awaiting the method you’re testing. To await it, you must make the unit test method return async Task. This example is a bit simplistic. In the real world when you are working with async methods, … Read more