C# – Join strings with a separator, ignoring nulls and empty strings

Normally when you want to join strings using a separator, you’d use string.Join(). However, the problem with string.Join() is it doesn’t ignore nulls or empty strings. Take a look at the following examples: If you want to filter out nulls and empty strings, you can filter the list of strings yourself and pass it into … 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

C# – Mapping nullable columns with SqlDataReader

When you have a database table with null columns, and you’re using SqlDataReader to map the results, there are a few things to do: Use nullable types in the model class. Example: instead of int use int? so the value can be null. Use SqlDataReader.IsDBNull() to check if you need to set the value to … Read more

TargetParameterCountException: Parameter count mismatch

When you are using reflection to call a method, you may run into this exception: System.Reflection.TargetParameterCountException: Parameter count mismatch. This exception is straightforward – you aren’t passing in the correct number of parameters to MethodInfo.Invoke(). This article shows three different cases where you might run into this exception when using reflection. Using reflection to invoke … 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 puts items from the right dictionary into the left dictionary. When duplicate keys exist, it’s keeping the value from the … Read more

System.InvalidOperationException: Sequence contains no elements

Problem When you call .First() on an empty IEnumerable, you get the following exception: System.InvalidOperationException: Sequence contains no elements Solution Option 1 – Use .FirstOrDefault() instead of .First() When the IEnumerable is empty, .FirstOrDefault() returns the default value for the type. For reference types this returns null. For value types this returns 0 or that … Read more