C# – How to create a custom exception

To create a custom exception, create a subclass of the Exception class, like this: Then throw it just like you would any other exception, like this: It’s a good idea to call the base constructor from your constructor and pass in your custom error message. If this exception is unhandled, or if you are logging … Read more

C# – Merge two dictionaries in-place

When you merge two dictionaries, you can either merge them in-place, or create a new dictionary and copy the values over to it. The following extension method does an in-place merge of two dictionaries. It loops through items in the right dictionary, adding them to the left dictionary. When duplicate keys exist, it’s keeping the … Read more

C# – How to use Assert.ThrowsException

Use Assert.ThrowsException<T>() in a unit test to verify that the code throws a specific type of exception. Here’s an example of asserting that ArgumentNullException is thrown: You specify the type of exception you’re expecting and then pass in a lambda that calls the code you’re testing. The assertion succeeds if and only if the code … Read more