C# – Using String.Join()

You can use String.Join() to convert a collection of items to a string with a separator (such as a comma). Here’s an example of using String.Join() to convert a List of strings to a comma-separated string: This results in the following comma-separated string: String.Join() can be used on wide variety of input: I’ll show a … Read more

C# – Convert an array to a list

The simplest way to convert an array to a list is with the ToList() Linq method: This outputs the following: The List<T> class stores data in a dynamically sized array. So converting an array to a list boils down to copying the array to the list’s internal array. That’s what ToList() does. It creates a … Read more

C# – Convert list to array

The simplest way to convert a list to an array is to use the List.ToArray() method: This outputs the following: Internally, the List<T> class stores elements in a dynamically sized array (it resizes when necessary). So under the hood, List.ToArray() uses Array.Copy() to copy the list’s internal array to a new array. This is very … Read more

C# – Serialize and deserialize a multidimensional array to JSON

System.Text.Json doesn’t support serializing / deserializing multidimensional arrays. When you try, it throws an exception like this – System.NotSupportedException: The type ‘System.Int[,] is not supported. You have three options: In this article, I’ll show an example of how to create a custom JsonConverter that handles multidimensional arrays. In this example, I’ll specifically show how to … Read more

C# – Pad a 2D array on all sides

Padding a 2D array on all sides means adding new rows on the top and bottom, new columns on the left and right, and then copying the original elements to the center of the padded array. It looks like this: There are two approaches for copying the elements. You can either copy individual items in … 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