C# – How to cancel an HttpClient request

It’s a good idea to provide users with a way to cancel a HttpClient request that’s taking too long. To be able to cancel an HttpClient request, you can pass in a CancellationToken: To get a CancellationToken, you have to create a CancellationTokenSource: To actually cancel the request, you have to call CancellationTokenSource.Cancel(): This means … Read more

ASP.NET Core – Getting query string values

The ASP.NET Core framework automatically parses query strings (i.e. ?name=Dune&year=2021) into HttpContext.Request.Query and maps the query string values to parameters in the action method (if you’ve added them). You can get the mapped query string values by adding action parameters, like this: Or you can use HttpContext.Request.Query directly (which is useful in many scenarios): This … Read more

C# – Sending query strings with HttpClient

Query strings start with ‘?’ and have one or more key-value pairs separated by ‘&’. All characters except a-z, A-Z, 0-9 have to be encoded, including Unicode characters. When you use HttpClient, it automatically encodes the URI for you (internally, it delegates this task to the Uri class). This means when you include a query … Read more

C# – Remove non-alphanumeric characters from a string

The simplest way to remove non-alphanumeric characters from a string is to use regex: Note: Don’t pass in a null, otherwise you’ll get an exception. Regex is the simplest options for removing characters by “category” (as opposed to removing arbitrary lists of characters or removing characters by position). The downside is that regex is the … Read more

C# – Convert a list to a dictionary

The simplest way to convert a list to a dictionary is to use the Linq ToDictionary() method: This loops through the list and uses the key/element selector lambdas you passed in to build the dictionary. In this article, I’ll go into details about how to use ToDictionary() and show how to deal with duplicate keys. … Read more

C# – Using reflection to get properties

You can get a list of a type’s properties using reflection, like this: Note: If you have an object, use movie.GetType().GetProperties() instead. This outputs the following: When you use GetProperties(), it returns a list of PropertyInfo objects. This gives you access the property’s definition (name, type, etc…) and allows you to get and modify its … Read more

Comparing performance with Benchmark.NET graphs

The following graph compares the execution time of three sort implementations ran against varying input sizes (1k, 10k, 100k): This graph was generated using Benchmark.NET, which I’ll show how to use in this article. I’ll be comparing the performance of multithreaded quicksort implementations (with the non-threaded Array.Sort() as a baseline). Create console app and reference … Read more