C# – Remove a set of characters from a string

The fastest and simplest way to remove a set of characters from a string is to use StringBuilder + List<char>, like this: I compared this with three other approaches. I did 100,000 iterations with a string with 2500 characters and a list of 15 characters to remove. This StringBuilder approach is almost 2x faster than … Read more

C# – Convert a list of strings into a set of enums

Let’s say you have a list of HTTP status codes that you read in when the service starts up (perhaps from appsettings.json or from the database). Whenever you send an HTTP request, you want to check if the returned status code is in this list of status code. To make things more efficient, you want … Read more

Algorithm Explained: Determine if two strings have a substring in common

Problem statement: Given two strings, determine if they have a substring in common. Example: Do “hello world” and “world” have a substring in common? Yes, they both have the substring “world”. Approach What are all the substrings of string? The string “word” is four characters long. It contains 10 substrings between length 1 and 4. … Read more

Set Operations – Intersect, Union, Difference, and Symmetric Difference

In the show House, different sets of main characters appeared in different seasons. For example, here are the main characters that starred in seasons 1 and 7: Characters in Season 1 Characters in Season 7 HouseCuddyWilsonForemanChaseCameron HouseCuddyWilsonForemanChaseTaubThirteenMasters Set operations allow you to answer interesting questions, such as “Which House main characters appeared in both seasons … Read more

C# – Exception filters – conditionally catch exceptions

In C# 6 they added exception filtering. This allows you to conditionally catch exceptions. To filter exceptions, you use the when clause after the catch clause, like this: Any SqlException that doesn’t meet the condition will not be caught. Previously, without exception filtering, you’d have to handle that scenario in the catch block and rethrow, … 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