C# – Nullable Reference Types feature basics

The main purpose of the Nullable Reference Types (NRT) feature is to help prevent NullReferenceExceptions by showing you compiler warnings. You can make a reference type nullable (ex: Movie? movie) or non-nullable (ex: Movie movie). This allows you to indicate how you plan on using these references. The compiler uses this info while analyzing actual … Read more

C# – Filter a dictionary

The simplest way to filter a dictionary is by using the Linq Where() + ToDictionary() methods. Here’s an example: Note: You can use the Dictionary constructor (new Dictionary<string, int>(filterList)) instead of ToDictionary() if you prefer. This produces a new dictionary with the filtered item: Where() produces a list (actually an IEnumerable) of KeyValuePair objects. Most … Read more

C# – Change a dictionary’s values in a foreach loop

In .NET 5 and above, you can loop through a dictionary and directly change its values. Here’s an example: This outputs the following: You couldn’t do this before .NET 5, because it would invalidate the enumerator and throw an exception: InvalidOperationException: Collection was modified; enumeration operation my not execute. Instead, you’d have to make the … Read more

C# – TimeZoneInfo with current UTC offset

TimeZoneInfo always shows the base UTC offset. This can be confusing because the UTC offset can change based on the date (due to daylight savings rules). Here’s an example showing DateTimeOffset and TimeZoneInfo with different offsets: You can get a date’s UTC offset from DateTimeOffset and combine it with TimeZoneInfo.DisplayName. This approach is implemented in … Read more

C# – How to use TimeZoneInfo

Time zones are complicated and their rules can change, so it makes sense to use a library when you’re dealing with them. One option in .NET is to use the built-in TimeZoneInfo class. Here’s an example of using TimeZoneInfo to get the local system’s time zone: This outputs: Note: The display name always show the … Read more

C# – Get the current date and time

Use DateTime.Now to get the current date/time, like this: This outputs the system’s current date/time: Note: By default, it uses the current culture’s date format (from the OS). This is showing the US date format – MM/dd/yyyy. DateTime.Now is the local date/time from the system where the code is executing. Keep that in mind if … Read more

C# – Loop through a dictionary

The simplest way to loop through a dictionary is with a foreach loop. Here’s an example of initializing a dictionary with values and then looping through it: This outputs the following: The loop variable is a KeyValuePair<string, int> with Key and Value properties. Instead of using this, you can deconstruct the KeyValuePair into named variables, … Read more

WinForms – Loop through a form’s controls

Forms also have a collection of controls (Controls property) that you can loop through. This is useful for when you want to do something to multiple controls and don’t want to have to manually type out code to deal with individual controls. Here’s an example of looping through a form’s top-level controls: Note: In the … Read more

CA2208: Instantiate argument exceptions correctly

The CA2208 code analysis rule checks for common mistakes when constructing argument exceptions. There are three main argument exception classes: ArgumentException, ArgumentNullException, and ArgumentOutOfRangeException. Unfortunately, it’s easy to make a mistake when using these. I’ll explain the common mistakes that CA2208 checks for and how to fix them (and when to suppress the warning instead). … Read more

C# – Get subclass properties with reflection

When you use reflection to get properties, you can get just the subclass properties by using BindingFlags.DeclaredOnly (this causes it to exclude inherited properties). Here’s an example: Note: Use GetType() if you have an object. Use typeof() if you have a class. The code outputs just the subclass properties (from the Driver subclass): Get base … Read more

C# – How to read problem details JSON with HttpClient

Problem details (RFC7807) is a standardized error response format that has a Content-Type of application/problem+json, an error response code (i.e. 400 – Bad Request), and has a response body that looks like this: This can be extended to include any number of properties. The example shown above comes from the default way ASP.NET Core returns … Read more

XML doc warnings: CS1573 and CS1572

I’ll show examples of the XML documentation warnings and how to fix them. CS1573 Parameter ‘X’ has no matching param tag in the XML comment (but other parameters do) Warning CS1573 means there’s a missing <param> tag for one of the method parameters. This usually happens when you add a new parameter (or rename one … Read more

C# – How to unit test a model validation attribute

You can unit test a validation attribute by creating an instance of it and then testing the two methods: In this article, I’ll show examples of unit testing these methods in a custom validation attribute and in a built-in validation attribute (i.e. [Range]). Unit testing a custom validation attribute Consider the following custom validation attribute … Read more

ASP.NET Core – Create a custom model validation attribute

There are many built-in model validation attributes available – such as [Required] and [Range] – which you can use to handle most validation scenarios. When these aren’t sufficient, you can create a custom validation attribute with your own validation logic. I’ll show an example of how to do that. 1 – Subclass ValidationAttribute and implement … Read more