C# – Convert string list to int list

You can convert a list of strings to a list of integers by using int.Parse() on all of the strings. There are two simple ways to do this: I’ll show examples of these using these methods and then explain how to handle parsing exceptions. Option 1 – Use List.ConvertAll() Here’s an example of how to … Read more

C# – Use string interpolation instead of string.Format

Using string.Format() is error prone and can lead to runtime exceptions. Using string interpolation prevents these problems (and it’s more readable). This article shows the two common mistakes you can make when using string.Format(), resulting in runtime exceptions, and shows how you can use string interpolation to prevent these problems. 1 – FormatException: Format string … 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# – How to test that your code can handle another culture’s date format

Let’s say you have code that converts a string to a DateTime with DateTime.Parse(): By default, DateTime.Parse() uses CultureInfo.CurrentCulture to figure out the date format. The current culture ultimately comes from your OS settings. So when you run this code on a computer that is using the en-US locale, the current culture will automatically default … Read more