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# – How to change the HttpClient timeout per request

It’s best practice to reuse the same HttpClient instance for multiple requests. When you’re using the same instance repeatedly, and you want to change the timeout per request, you can pass in a CancellationToken, like this: You can’t change HttpClient.Timeout after the instance has been used. You have to pass in a CancellationToken instead. There … Read more

CellContentClick throws ArgumentOutOfRangeException when user clicks on the column header

Problem In a WinForm project, you’re using a DataGridView control and are handling the CellContentClick event. When the user clicks the column header, the following exception is thrown: System.ArgumentOutOfRangeException: ‘Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index’ The problem is that when the user clicks … Read more

ArgumentOutOfRangeException: InvalidArgument=Value of 0 is not valid for SelectedIndex

Problem Let’s say you’re initializing a ComboBox like this: And you get the following exception: System.ArgumentOutOfRangeException: ‘InvalidArgument=Value of ‘0’ is not valid for ‘SelectedIndex’. (Parameter ‘value’)Actual value was 0.’ You’re getting this exception because the DataSource is empty. Solution Are you expecting there to always be data? If you’re expecting there to always be data, … Read more